def test_historical_pricing(mocker):
    with MockCalc(mocker):
        swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate='ATM+1', name='10y@a+1')
        swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate='ATM+2', name='10y@a+2')
        swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate='ATM+3', name='10y@a+3')

        portfolio = Portfolio((swap1, swap2, swap3))
        dates = (dt.date(2021, 2, 9), dt.date(2021, 2, 10), dt.date(2021, 2, 11))

        with HistoricalPricingContext(dates=dates) as hpc:
            risk_key = hpc._PricingContext__risk_key(risk.DollarPrice, swap1.provider)
            results = portfolio.calc((risk.DollarPrice, risk.IRDelta))

        expected = risk.SeriesWithInfo(
            pd.Series(
                data=[-580316.7895084377, -580373.4091600645, -580811.1441974249],
                index=[dt.date(2021, 2, 9), dt.date(2021, 2, 10), dt.date(2021, 2, 11)]
            ),
            risk_key=historical_risk_key(risk_key), )

        assert results.dates == dates
        actual = results[risk.DollarPrice].aggregate()
        assert actual.equals(expected)

        assert (results[dt.date(2021, 2, 9)][risk.DollarPrice]['10y@a+1'] ==
                results[risk.DollarPrice][dt.date(2021, 2, 9)]['10y@a+1'])
        assert (results[dt.date(2021, 2, 9)][risk.DollarPrice]['10y@a+1'] ==
                results[risk.DollarPrice]['10y@a+1'][dt.date(2021, 2, 9)])
        assert (results[dt.date(2021, 2, 9)][risk.DollarPrice]['10y@a+1'] ==
                results['10y@a+1'][risk.DollarPrice][dt.date(2021, 2, 9)])
        assert (results[dt.date(2021, 2, 9)][risk.DollarPrice]['10y@a+1'] ==
                results['10y@a+1'][dt.date(2021, 2, 9)][risk.DollarPrice])
        assert (results[dt.date(2021, 2, 9)][risk.DollarPrice]['10y@a+1'] ==
                results[dt.date(2021, 2, 9)]['10y@a+1'][risk.DollarPrice])
Beispiel #2
0
def test_backtothefuture_pricing(mocker):
    with MockCalc(mocker):
        swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
        swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
        swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

        portfolio = Portfolio((swap1, swap2, swap3))
        pricing_date = dt.date(2020, 10, 7)
        with PricingContext(pricing_date=pricing_date):
            with BackToTheFuturePricingContext(dates=business_day_offset(
                    pricing_date, [-1, 0, 1], roll='forward')) as hpc:
                risk_key = hpc._PricingContext__risk_key(
                    risk.DollarPrice, swap1.provider)
                results = portfolio.calc(risk.DollarPrice)

    expected = risk.SeriesWithInfo(
        pd.Series(
            data=[-35280379.86540368, -35348910.76427929, -30830994.939595155],
            index=business_day_offset(pricing_date, [-1, 0, 1],
                                      roll='forward')),
        risk_key=risk_key.ex_date_and_market,
    )

    actual = results[risk.DollarPrice].aggregate()

    assert actual.equals(expected)
Beispiel #3
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
Beispiel #4
0
def test_backtothefuture_pricing(mocker):
    with MockCalc(mocker):
        swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
        swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
        swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

        portfolio = Portfolio((swap1, swap2, swap3))
        pricing_date = dt.date(2021, 2, 10)
        with PricingContext(pricing_date=pricing_date):
            with BackToTheFuturePricingContext(dates=business_day_offset(
                    pricing_date, [-1, 0, 1], roll='forward')) as hpc:
                risk_key = hpc._PricingContext__risk_key(
                    risk.DollarPrice, swap1.provider)
                results = portfolio.calc(risk.DollarPrice)

    expected = risk.SeriesWithInfo(
        pd.Series(
            data=[-22711963.80864744, -22655907.930484552, -21582551.58922608],
            index=business_day_offset(pricing_date, [-1, 0, 1],
                                      roll='forward')),
        risk_key=historical_risk_key(risk_key),
    )

    actual = results[risk.DollarPrice].aggregate()

    assert actual.equals(expected)
Beispiel #5
0
def test_unnamed_portfolio(mocker):
    unnamed_1 = Portfolio((swap_1, swap_2))
    unnamed_2 = Portfolio((swap_3, swap_4))
    unnamed = Portfolio((unnamed_1, unnamed_2))
    with MockCalc(mocker):
        res = unnamed.calc(risk.IRFwdRate)
        df = res.to_frame()
        assert len(df) == 2
        assert list(df.index) == ['Portfolio_0', 'Portfolio_1']
        assert list(df.columns) == ['5y', '10y']
Beispiel #6
0
def test_single_instrument_new_mock(mocker):
    with MockCalc(mocker):
        with PricingContext(pricing_date=dt.date(2020, 10, 15)):
            swap1 = IRSwap('Pay', '10y', 'USD', name='swap1')

            portfolio = Portfolio(swap1)
            fwd: PortfolioRiskResult = portfolio.calc(risk.IRFwdRate)

        assert portfolio.paths('swap1') == (PortfolioPath(0), )
        assert tuple(map(lambda x: round(x, 6), fwd)) == (0.007512, )
        assert round(fwd.aggregate(), 2) == 0.01
        assert round(fwd[swap1], 6) == 0.007512
Beispiel #7
0
def test_portfolio_overrides(mocker):
    swap_1 = IRSwap("Pay", "5y", "EUR", fixed_rate=-0.005, name="5y")
    swap_2 = IRSwap("Pay", "10y", "EUR", fixed_rate=-0.005, name="10y")
    swap_3 = IRSwap("Pay", "5y", "GBP", fixed_rate=-0.005, name="5y")
    swap_4 = IRSwap("Pay", "10y", "GBP", fixed_rate=-0.005, name="10y")
    eur_port = Portfolio([swap_1, swap_2], name="EUR")
    gbp_port = Portfolio([swap_3, swap_4], name="GBP")

    # override instruments after portfolio construction
    for idx in range(len(eur_port)):
        eur_port[idx].fixed_rate = eur_port[idx].fixed_rate - 0.0005

    assert eur_port[swap_1] is not None

    with MockCalc(mocker):
        # override instruments after portfolio construction and resolution
        gbp_port.resolve()
        for idx in range(len(gbp_port)):
            gbp_port[idx].notional_amount = gbp_port[idx].notional_amount - 1

        with PricingContext(dt.date(2020, 1, 14)):
            r1 = eur_port.calc(risk.Price)
            r2 = eur_port.calc((risk.Price, risk.DollarPrice))
            r3 = gbp_port.calc(risk.Price)
            r4 = gbp_port.calc((risk.DollarPrice, risk.Price))

    assert gbp_port[swap_3] is not None

    assert r1[eur_port[0]] is not None
    assert r1['5y'] is not None
    assert r1.to_frame() is not None
    assert r2[eur_port[0]] is not None
    assert r2[risk.Price][0] is not None
    assert r2[0][risk.Price] is not None
    assert r3[gbp_port[0]] is not None
    assert r3.to_frame() is not None
    assert r4[gbp_port[0]] is not None
    assert r4[risk.DollarPrice][0] is not None
    assert r4[0][risk.DollarPrice] is not None
Beispiel #8
0
def test_backtothefuture_pricing(mocker):
    set_session()

    day1 = [
        [
            [{'$type': 'Risk', 'val': 0.01}],
            [{'$type': 'Risk', 'val': 0.02}],
            [{'$type': 'Risk', 'val': 0.03}],
        ]
    ]

    day2 = [
        [
            [{'$type': 'Risk', 'val': 0.011}],
            [{'$type': 'Risk', 'val': 0.021}],
            [{'$type': 'Risk', 'val': 0.031}],
        ]
    ]

    day3 = [
        [
            [{'$type': 'Risk', 'val': 0.012}],
            [{'$type': 'Risk', 'val': 0.022}],
            [{'$type': 'Risk', 'val': 0.032}],
        ]
    ]

    mocker.return_value = [day1, day2, day3]

    swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
    swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
    swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    with BackToTheFuturePricingContext(dates=business_day_offset(dt.datetime.today().date(), [-1, 0, 1],
                                                                 roll='forward')) as hpc:
        risk_key = hpc._PricingContext__risk_key(risk.DollarPrice, swap1.provider)
        results = portfolio.calc(risk.DollarPrice)

    expected = risk.SeriesWithInfo(
        pd.Series(
            data=[0.06, 0.063, 0.066],
            index=business_day_offset(dt.datetime.today().date(), [-1, 0, 1], roll='forward')
        ),
        risk_key=risk_key.ex_date_and_market,)

    actual = results[risk.DollarPrice].aggregate()

    assert actual.equals(expected)
Beispiel #9
0
def test_duplicate_instrument(mocker):
    with MockCalc(mocker):
        swap1 = IRSwap('Pay', '1y', 'EUR', name='EUR1y')
        swap2 = IRSwap('Pay', '2y', 'EUR', name='EUR2y')
        swap3 = IRSwap('Pay', '3y', 'EUR', name='EUR3y')

        portfolio = Portfolio((swap1, swap2, swap3, swap1))
        assert portfolio.paths('EUR1y') == (PortfolioPath(0), PortfolioPath(3))
        assert portfolio.paths('EUR2y') == (PortfolioPath(1), )
        with PricingContext(pricing_date=dt.date(2020, 10, 15)):
            fwds: PortfolioRiskResult = portfolio.calc(risk.IRFwdRate)

        assert tuple(map(lambda x: round(x, 6),
                         fwds)) == (-0.005378, -0.005224, -0.00519, -0.005378)
        assert round(fwds.aggregate(), 6) == -0.02117
        assert round(fwds[swap1], 6) == -0.005378
Beispiel #10
0
def test_portfolio(mocker):

    with MockCalc(mocker):
        with PricingContext(pricing_date=dt.date(2020, 10, 15)):
            swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.001, name='swap_10y@10bp')
            swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.002, name='swap_10y@20bp')
            swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.003, name='swap_10y@30bp')

            portfolio = Portfolio((swap1, swap2, swap3))

            prices: PortfolioRiskResult = portfolio.dollar_price()
            result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

        assert tuple(sorted(map(lambda x: round(x, 0), prices))) == (4439478.0, 5423405.0, 6407332.0)
        assert round(prices.aggregate(), 2) == 16270214.48
        assert round(prices[0], 0) == 6407332.0
        assert round(prices[swap2], 0) == 5423405.0
        assert round(prices['swap_10y@30bp'], 0) == 4439478.0

        assert tuple(map(lambda x: round(x, 0), result[risk.DollarPrice])) == (6407332.0, 5423405.0, 4439478.0)
        assert round(result[risk.DollarPrice].aggregate(), 0) == 16270214.0
        assert round(result[risk.DollarPrice]['swap_10y@30bp'], 0) == 4439478.0
        assert round(result[risk.DollarPrice]['swap_10y@30bp'], 0) == round(result['swap_10y@30bp'][risk.DollarPrice],
                                                                            0)

        assert round(result[risk.IRDelta].aggregate().value.sum(), 0) == 278977.0

        prices_only = result[risk.DollarPrice]
        assert tuple(map(lambda x: round(x, 0), prices)) == tuple(map(lambda x: round(x, 0), prices_only))

        swap4 = IRSwap('Pay', '10y', 'USD', fixed_rate=-0.001, name='swap_10y@-10bp')
        portfolio.append(swap4)
        assert len(portfolio.instruments) == 4

        extracted_swap = portfolio.pop('swap_10y@20bp')
        assert extracted_swap == swap2
        assert len(portfolio.instruments) == 3

        swap_dict = {'swap_5': swap1,
                     'swap_6': swap2,
                     'swap_7': swap3}

        portfolio = Portfolio(swap_dict)
        assert len(portfolio) == 3
Beispiel #11
0
def test_historical_pricing(mocker):
    with MockCalc(mocker):
        swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate='ATM+1', name='10y@a+1')
        swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate='ATM+2', name='10y@a+2')
        swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate='ATM+3', name='10y@a+3')

        portfolio = Portfolio((swap1, swap2, swap3))
        dates = (dt.date(2019, 10, 7), dt.date(2019, 10,
                                               8), dt.date(2019, 10, 9))

        with HistoricalPricingContext(dates=dates) as hpc:
            risk_key = hpc._PricingContext__risk_key(risk.DollarPrice,
                                                     swap1.provider)
            results = portfolio.calc((risk.DollarPrice, risk.IRDelta))

        expected = risk.SeriesWithInfo(
            pd.Series(data=[
                -564854.3640043903, -565604.2636791412, -564751.5121349357
            ],
                      index=[
                          dt.date(2019, 10, 7),
                          dt.date(2019, 10, 8),
                          dt.date(2019, 10, 9)
                      ]),
            risk_key=risk_key.ex_date_and_market,
        )

        assert results.dates == dates
        actual = results[risk.DollarPrice].aggregate()
        assert actual.equals(expected)

        assert (results[dt.date(2019, 10, 9)][risk.DollarPrice]['10y@a+1'] ==
                results[risk.DollarPrice][dt.date(2019, 10, 9)]['10y@a+1'])
        assert (results[dt.date(2019, 10, 9)][risk.DollarPrice]['10y@a+1'] ==
                results[risk.DollarPrice]['10y@a+1'][dt.date(2019, 10, 9)])
        assert (results[dt.date(2019, 10, 9)][risk.DollarPrice]['10y@a+1'] ==
                results['10y@a+1'][risk.DollarPrice][dt.date(2019, 10, 9)])
        assert (results[dt.date(
            2019, 10,
            9)][risk.DollarPrice]['10y@a+1'] == results['10y@a+1'][dt.date(
                2019, 10, 9)][risk.DollarPrice])
        assert (results[dt.date(
            2019, 10, 9)][risk.DollarPrice]['10y@a+1'] == results[dt.date(
                2019, 10, 9)]['10y@a+1'][risk.DollarPrice])
Beispiel #12
0
def test_portfolio(mocker):
    set_session()

    dollar_price_values = [[[{
        'date': '2019-10-07',
        'value': 0.01
    }], [{
        'date': '2019-10-07',
        'value': 0.02
    }], [{
        'date': '2019-10-07',
        'value': 0.03
    }]]]

    dollar_price_ir_delta_values = [[[{
        'date': '2019-10-07',
        'value': 0.01
    }], [{
        'date': '2019-10-07',
        'value': 0.02
    }], [{
        'date': '2019-10-07',
        'value': 0.03
    }]],
                                    [[{
                                        'date': '2019-10-07',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '1y',
                                        'value': 0.01
                                    }, {
                                        'date': '2019-10-07',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '2y',
                                        'value': 0.015
                                    }],
                                     [{
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.02
                                     }, {
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.025
                                     }],
                                     [{
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.03
                                     }, {
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.035
                                     }]]]

    swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
    swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
    swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    mocker.return_value = dollar_price_values
    prices: PortfolioRiskResult = portfolio.dollar_price()
    assert tuple(sorted(prices)) == (0.01, 0.02, 0.03)
    assert round(prices.aggregate(), 2) == 0.06
    assert prices[0] == 0.01
    assert prices[swap2] == 0.02
    assert prices['swap3'] == 0.03

    mocker.return_value = dollar_price_ir_delta_values
    result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

    assert tuple(result[risk.DollarPrice]) == (0.01, 0.02, 0.03)
    assert result[risk.DollarPrice].aggregate() == 0.06
    assert result[risk.DollarPrice]['swap3'] == 0.03
    assert result[risk.DollarPrice]['swap3'] == result['swap3'][
        risk.DollarPrice]

    expected = risk.aggregate_risk(
        [pd.DataFrame(v) for v in dollar_price_ir_delta_values[1]])
    assert result[risk.IRDelta].aggregate().equals(expected)

    prices_only = result[risk.DollarPrice]
    assert tuple(prices) == tuple(prices_only)
Beispiel #13
0
def test_results_with_resolution():
    set_session()

    dollar_price_ir_delta_values = [[[{
        '$type': 'Risk',
        'val': 0.01
    }], [{
        '$type': 'Risk',
        'val': 0.02
    }], [{
        '$type': 'Risk',
        'val': 0.03
    }]],
                                    [[{
                                        '$type':
                                        'RiskVector',
                                        'asset': [0.01, 0.015],
                                        'points': [{
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '1y'
                                        }, {
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '2y'
                                        }]
                                    }],
                                     [{
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.02, 0.025],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }],
                                     [{
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.03, 0.035],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }]]]

    swap1 = IRSwap('Pay', '10y', 'USD', name='swap1')
    swap2 = IRSwap('Pay', '10y', 'GBP', name='swap2')
    swap3 = IRSwap('Pay', '10y', 'EUR', name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    with mock.patch('gs_quant.api.gs.risk.GsRiskApi._exec') as mocker:
        mocker.return_value = [dollar_price_ir_delta_values]
        result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

    # Check that we've got results
    assert result[swap1][risk.DollarPrice] is not None

    # Now resolve portfolio and assert that we can still get the result

    resolution_values = [[[{
        '$type': 'LegDefinition',
        'fixedRate': 0.01
    }], [{
        '$type': 'LegDefinition',
        'fixedRate': 0.007
    }], [{
        '$type': 'LegDefinition',
        'fixedRate': 0.05
    }]]]

    orig_swap1 = swap1.clone()

    with mock.patch('gs_quant.api.gs.risk.GsRiskApi._exec') as mocker:
        mocker.return_value = [resolution_values]
        portfolio.resolve()

    # Assert that the resolved swap is indeed different and that we can retrieve results by both

    assert swap1 != orig_swap1
    assert result[swap1][risk.DollarPrice] is not None
    assert result[orig_swap1][risk.DollarPrice] is not None

    # Now reset the instruments and portfolio

    swap1 = IRSwap('Pay', '10y', 'USD', name='swap1')
    swap2 = IRSwap('Pay', '10y', 'GBP', name='swap2')
    swap3 = IRSwap('Pay', '10y', 'EUR', name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3, swap1))

    with mock.patch('gs_quant.api.gs.risk.GsRiskApi._exec') as mocker:
        with PricingContext(dt.date(1066, 11, 14)):
            # Resolve under a different pricing date
            mocker.return_value = [resolution_values]
            portfolio.resolve()

    # Assert that after resolution under a different context, we cannot retrieve the result

    try:
        _ = result[swap1][risk.DollarPrice]
        assert False
    except KeyError:
        assert True
Beispiel #14
0
def test_portfolio(mocker):
    set_session()

    dollar_price_values = [[[{
        '$type': 'Risk',
        'val': 0.01
    }], [{
        '$type': 'Risk',
        'val': 0.02
    }], [{
        '$type': 'Risk',
        'val': 0.03
    }]]]

    dollar_price_ir_delta_values = [[[{
        '$type': 'Risk',
        'val': 0.01
    }], [{
        '$type': 'Risk',
        'val': 0.02
    }], [{
        '$type': 'Risk',
        'val': 0.03
    }]],
                                    [[{
                                        '$type':
                                        'RiskVector',
                                        'asset': [0.01, 0.015],
                                        'points': [{
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '1y'
                                        }, {
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '2y'
                                        }]
                                    }],
                                     [{
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.02, 0.025],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }],
                                     [{
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.03, 0.035],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }]]]

    swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
    swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
    swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    mocker.return_value = [dollar_price_values]
    prices: PortfolioRiskResult = portfolio.dollar_price()
    assert tuple(sorted(prices)) == (0.01, 0.02, 0.03)
    assert round(prices.aggregate(), 2) == 0.06
    assert prices[0] == 0.01
    assert prices[swap2] == 0.02
    assert prices['swap3'] == 0.03

    mocker.return_value = [dollar_price_ir_delta_values]
    result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

    assert tuple(result[risk.DollarPrice]) == (0.01, 0.02, 0.03)
    assert result[risk.DollarPrice].aggregate() == 0.06
    assert result[risk.DollarPrice]['swap3'] == 0.03
    assert result[risk.DollarPrice]['swap3'] == result['swap3'][
        risk.DollarPrice]

    assert result[risk.IRDelta].aggregate().value.sum() == 0.135

    prices_only = result[risk.DollarPrice]
    assert tuple(prices) == tuple(prices_only)

    swap4 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap4')
    portfolio.append(swap4)
    assert len(portfolio.instruments) == 4

    extracted_swap = portfolio.pop('swap2')
    assert extracted_swap == swap2
    assert len(portfolio.instruments) == 3

    swap_dict = {'swap_5': swap1, 'swap_6': swap2, 'swap_7': swap3}

    portfolio = Portfolio(swap_dict)
    assert len(portfolio) == 3
Beispiel #15
0
def test_historical_pricing(mocker):
    set_session()

    dollar_price_ir_delta_values = [[[{
        '$type': 'Risk',
        'val': 0.01
    }, {
        '$type': 'Risk',
        'val': 0.011
    }, {
        '$type': 'Risk',
        'val': 0.012
    }],
                                     [{
                                         '$type': 'Risk',
                                         'val': 0.02
                                     }, {
                                         '$type': 'Risk',
                                         'val': 0.021
                                     }, {
                                         '$type': 'Risk',
                                         'val': 0.022
                                     }],
                                     [{
                                         '$type': 'Risk',
                                         'val': 0.03
                                     }, {
                                         '$type': 'Risk',
                                         'val': 0.031
                                     }, {
                                         '$type': 'Risk',
                                         'val': 0.032
                                     }]],
                                    [[{
                                        '$type':
                                        'RiskVector',
                                        'asset': [0.01, 0.015],
                                        'points': [{
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '1y'
                                        }, {
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '2y'
                                        }]
                                    }, {
                                        '$type':
                                        'RiskVector',
                                        'asset': [0.011, 0.0151],
                                        'points': [{
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '1y'
                                        }, {
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '2y'
                                        }]
                                    }, {
                                        '$type':
                                        'RiskVector',
                                        'asset': [0.012, 0.0152],
                                        'points': [{
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '1y'
                                        }, {
                                            'type': 'IR',
                                            'asset': 'USD',
                                            'class_': 'Swap',
                                            'point': '2y'
                                        }]
                                    }],
                                     [{
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.02, 0.025],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }, {
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.021, 0.0251],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }, {
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.022, 0.0252],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }],
                                     [{
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.03, 0.035],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }, {
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.031, 0.0351],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }, {
                                         '$type':
                                         'RiskVector',
                                         'asset': [0.032, 0.0352],
                                         'points': [{
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '1y'
                                         }, {
                                             'type': 'IR',
                                             'asset': 'USD',
                                             'class_': 'Swap',
                                             'point': '2y'
                                         }]
                                     }]]]

    mocker.return_value = [dollar_price_ir_delta_values]

    swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
    swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
    swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    with HistoricalPricingContext(dates=(dt.date(2019, 10, 7),
                                         dt.date(2019, 10, 8),
                                         dt.date(2019, 10, 9))) as hpc:
        risk_key = hpc._PricingContext__risk_key(risk.DollarPrice,
                                                 swap1.provider())
        results = portfolio.calc((risk.DollarPrice, risk.IRDelta))

    expected = risk.SeriesWithInfo(
        pd.Series(data=[0.06, 0.063, 0.066],
                  index=[
                      dt.date(2019, 10, 7),
                      dt.date(2019, 10, 8),
                      dt.date(2019, 10, 9)
                  ]),
        risk_key=risk_key.base,
    )

    actual = results[risk.DollarPrice].aggregate()

    assert actual.equals(expected)
Beispiel #16
0
def test_historical_pricing(mocker):
    set_session()

    dollar_price_ir_delta_values = [[[{
        'date': '2019-10-07',
        'value': 0.01
    }, {
        'date': '2019-10-08',
        'value': 0.011
    }, {
        'date': '2019-10-09',
        'value': 0.012
    }],
                                     [{
                                         'date': '2019-10-07',
                                         'value': 0.02
                                     }, {
                                         'date': '2019-10-08',
                                         'value': 0.021
                                     }, {
                                         'date': '2019-10-09',
                                         'value': 0.022
                                     }],
                                     [{
                                         'date': '2019-10-07',
                                         'value': 0.03
                                     }, {
                                         'date': '2019-10-08',
                                         'value': 0.031
                                     }, {
                                         'date': '2019-10-09',
                                         'value': 0.032
                                     }]],
                                    [[{
                                        'date': '2019-10-07',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '1y',
                                        'value': 0.01
                                    }, {
                                        'date': '2019-10-07',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '2y',
                                        'value': 0.015
                                    }, {
                                        'date': '2019-10-08',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '1y',
                                        'value': 0.011
                                    }, {
                                        'date': '2019-10-08',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '2y',
                                        'value': 0.0151
                                    }, {
                                        'date': '2019-10-09',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '1y',
                                        'value': 0.012
                                    }, {
                                        'date': '2019-10-09',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '2y',
                                        'value': 0.0152
                                    }],
                                     [{
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.02
                                     }, {
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.025
                                     }, {
                                         'date': '2019-10-08',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.021
                                     }, {
                                         'date': '2019-10-08',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.0251
                                     }, {
                                         'date': '2019-10-09',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.022
                                     }, {
                                         'date': '2019-10-09',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.0252
                                     }],
                                     [{
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.03
                                     }, {
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.035
                                     }, {
                                         'date': '2019-10-08',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.031
                                     }, {
                                         'date': '2019-10-08',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.0351
                                     }, {
                                         'date': '2019-10-09',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.032
                                     }, {
                                         'date': '2019-10-09',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.0352
                                     }]]]

    mocker.return_value = dollar_price_ir_delta_values

    swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
    swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
    swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    with HistoricalPricingContext(3):
        results = portfolio.calc((risk.DollarPrice, risk.IRDelta))

    expected = pd.Series(data=[0.06, 0.063, 0.066],
                         index=[
                             dt.date(2019, 10, 7),
                             dt.date(2019, 10, 8),
                             dt.date(2019, 10, 9)
                         ])

    assert results[risk.DollarPrice].aggregate().equals(expected)
Beispiel #17
0
def test_portfolio(mocker):
    set_session()

    dollar_price_values = [[[{
        'date': '2019-10-07',
        'value': 0.01
    }], [{
        'date': '2019-10-07',
        'value': 0.02
    }], [{
        'date': '2019-10-07',
        'value': 0.03
    }]]]

    dollar_price_ir_delta_values = [[[{
        'date': '2019-10-07',
        'value': 0.01
    }], [{
        'date': '2019-10-07',
        'value': 0.02
    }], [{
        'date': '2019-10-07',
        'value': 0.03
    }]],
                                    [[{
                                        'date': '2019-10-07',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '1y',
                                        'value': 0.01
                                    }, {
                                        'date': '2019-10-07',
                                        'marketDataType': 'IR',
                                        'assetId': 'USD',
                                        'pointClass': 'Swap',
                                        'point': '2y',
                                        'value': 0.015
                                    }],
                                     [{
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.02
                                     }, {
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.025
                                     }],
                                     [{
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '1y',
                                         'value': 0.03
                                     }, {
                                         'date': '2019-10-07',
                                         'marketDataType': 'IR',
                                         'assetId': 'USD',
                                         'pointClass': 'Swap',
                                         'point': '2y',
                                         'value': 0.035
                                     }]]]

    swap1 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap1')
    swap2 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.02, name='swap2')
    swap3 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.03, name='swap3')

    portfolio = Portfolio((swap1, swap2, swap3))

    mocker.return_value = dollar_price_values
    prices: PortfolioRiskResult = portfolio.dollar_price()
    assert tuple(sorted(prices)) == (0.01, 0.02, 0.03)
    assert round(prices.aggregate(), 2) == 0.06
    assert prices[0] == 0.01
    assert prices[swap2] == 0.02
    assert prices['swap3'] == 0.03

    mocker.return_value = dollar_price_ir_delta_values
    result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

    assert tuple(result[risk.DollarPrice]) == (0.01, 0.02, 0.03)
    assert result[risk.DollarPrice].aggregate() == 0.06
    assert result[risk.DollarPrice]['swap3'] == 0.03
    assert result[risk.DollarPrice]['swap3'] == result['swap3'][
        risk.DollarPrice]

    expected = risk.aggregate_risk([
        risk.DataFrameWithInfo(PricingContext.current.pricing_key,
                               pd.DataFrame(v))
        for v in dollar_price_ir_delta_values[1]
    ]).reset_index(drop=True)
    actual = result[risk.IRDelta].aggregate().raw_value
    assert actual.equals(expected)

    prices_only = result[risk.DollarPrice]
    assert tuple(prices) == tuple(prices_only)

    swap4 = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01, name='swap4')
    portfolio.append(swap4)
    assert len(portfolio.instruments) == 4

    extracted_swap = portfolio.pop('swap2')
    assert extracted_swap == swap2
    assert len(portfolio.instruments) == 3

    swap_dict = {'swap_5': swap1, 'swap_6': swap2, 'swap_7': swap3}

    portfolio = Portfolio(swap_dict)
    assert len(portfolio) == 3
Beispiel #18
0
def test_results_with_resolution(mocker):
    with MockCalc(mocker):

        swap1 = IRSwap('Pay', '10y', 'USD', name='swap1')
        swap2 = IRSwap('Pay', '10y', 'GBP', name='swap2')
        swap3 = IRSwap('Pay', '10y', 'EUR', name='swap3')

        portfolio = Portfolio((swap1, swap2, swap3))

        with PricingContext(pricing_date=dt.date(2020, 10, 15)):
            result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

        # Check that we've got results
        assert result[swap1][risk.DollarPrice] is not None

        # Now resolve portfolio and assert that we can still get the result

        orig_swap1 = swap1.clone()

        with PricingContext(pricing_date=dt.date(2020, 10, 15)):
            portfolio.resolve()

        # Assert that the resolved swap is indeed different and that we can retrieve results by both

        assert swap1 != orig_swap1
        assert result[swap1][risk.DollarPrice] is not None
        assert result[orig_swap1][risk.DollarPrice] is not None

        # Now reset the instruments and portfolio

        swap1 = IRSwap('Pay', '10y', 'USD', name='swap1')
        swap2 = IRSwap('Pay', '10y', 'GBP', name='swap2')
        swap3 = IRSwap('Pay', '10y', 'EUR', name='swap3')

        portfolio = Portfolio((swap1, swap2, swap3, swap1))

        with PricingContext(dt.date(2020, 10, 14)):
            # Resolve under a different pricing date
            portfolio.resolve()

        assert portfolio.instruments[0].termination_date == dt.date(
            2030, 10, 16)
        assert portfolio.instruments[1].termination_date == dt.date(
            2030, 10, 14)
        assert round(swap1.fixed_rate, 4) == 0.0075
        assert round(swap2.fixed_rate, 4) == 0.004
        assert round(swap3.fixed_rate, 4) == -0.0027

        # Assert that after resolution under a different context, we cannot retrieve the result

        try:
            _ = result[swap1][risk.DollarPrice]
            assert False
        except KeyError:
            assert True

        # Resolve again and check we get the same values

        with PricingContext(dt.date(2020, 10, 14)):
            # Resolve under a different pricing date
            portfolio.resolve()

        assert portfolio.instruments[0].termination_date == dt.date(
            2030, 10, 16)
        assert portfolio.instruments[1].termination_date == dt.date(
            2030, 10, 14)
        assert round(swap1.fixed_rate, 4) == 0.0075
        assert round(swap2.fixed_rate, 4) == 0.004
        assert round(swap3.fixed_rate, 4) == -0.0027
Beispiel #19
0
from gs_quant.common import PayReceive, Currency  # import constants
from gs_quant.instrument import IRSwaption  # import instruments
from gs_quant.markets.portfolio import Portfolio
import gs_quant.risk as risk
from gs_quant.session import Environment, GsSession  # import sessions

client_id = None  # Supply your application id
client_secret = None  # Supply your client secret
scopes = ('run_analytics', )
GsSession.use(Environment.PROD, client_id, client_secret, scopes)

swaption1 = IRSwaption(PayReceive.Pay,
                       '5y',
                       Currency.EUR,
                       expiration_date='3m',
                       name='EUR-3m5y')
swaption2 = IRSwaption(PayReceive.Pay,
                       '5y',
                       Currency.EUR,
                       expiration_date='6m',
                       name='EUR-6m5y')
portfolio = Portfolio((swaption1, swaption2))
result = portfolio.calc((risk.DollarPrice, risk.IRDelta))

# instrument risk
print(result[risk.DollarPrice]['EUR-3m5y'])
print(result['EUR-3m5y'][risk.DollarPrice])

# portfolio risk
print(result[risk.IRDelta].aggregate())