Exemplo n.º 1
0
    def test_cleanup_properly(self):
        r = Replacer()
        try:
            m = Mock()
            d = mkdtemp()
            m.return_value = d
            r.replace('testfixtures.tempdirectory.mkdtemp', m)

            self.failUnless(os.path.exists(d))

            self.assertFalse(m.called)

            @tempdir()
            def test_method(d):
                d.write('something', b'stuff')
                d.compare(['something'])

            self.assertFalse(m.called)
            compare(os.listdir(d), [])

            test_method()

            self.assertTrue(m.called)
            self.failIf(os.path.exists(d))

        finally:
            r.restore()
            if os.path.exists(d):
                # only runs if the test fails!
                rmtree(d)  # pragma: no cover
Exemplo n.º 2
0
 def test_list_subclass_strict(self):
     m = Mock()
     m.aCall()
     self.check_raises(
         [call.aCall()], m.method_calls,
         ("[call.aCall()] (<{0} 'list'>) != [call.aCall()] "
          "({1})").format(class_type_name, call_list_repr),
         strict=True,
         )
Exemplo n.º 3
0
 def test_list_subclass_long_strict(self):
     m = Mock()
     m.call('X'*20)
     self.check_raises(
         [call.call('Y'*20)], m.method_calls,
         ("[call.call('YYYYYYYYYYYYYYYYYY... "
          "(<{0} 'list'>) != "
          "[call.call('XXXXXXXXXXXXXXXXXX... "
          "({1})").format(class_type_name, call_list_repr),
         strict=True,
         )
Exemplo n.º 4
0
    def test_strict_comparer_supplied(self):

        compare_obj = Mock()
        compare_obj.return_value = 'not equal'

        self.check_raises(
            object(), object(),
            "not equal",
            strict=True,
            comparers={object: compare_obj},
            )
Exemplo n.º 5
0
    def test_calls_different(self):
        m1 =Mock()
        m2 =Mock()
        m1.foo(1, 2, x=3, y=4)
        m2.bar(1, 3, x=7, y=4)

        self.check_raises(
            m1.mock_calls,
            m2.mock_calls,
            "sequence not as expected:\n"
            "\n"
            "same:\n"
            "[]\n"
            "\n"
            "first:\n"
            "[call.foo(1, 2, x=3, y=4)]\n"
            "\n"
            "second:\n"
            "[call.bar(1, 3, x=7, y=4)]"
            "\n\n"
            'While comparing [0]: \n'
            "'call.foo(1, 2, x=3, y=4)'\n"
            '!=\n'
            "'call.bar(1, 3, x=7, y=4)'"
        )
Exemplo n.º 6
0
    def test_wrapping_different_functions(self):

        m = Mock()

        @wrap(m.before1, m.after1)
        def test_function1():
            m.something1()
            return 'something1'

        @wrap(m.before2, m.after2)
        def test_function2():
            m.something2()
            return 'something2'

        compare(m.method_calls, [])
        compare(test_function1(), 'something1')
        compare(m.method_calls, [('before1', (), {}), ('something1', (), {}),
                                 ('after1', (), {})])
        compare(test_function2(), 'something2')
        compare(m.method_calls, [('before1', (), {}), ('something1', (), {}),
                                 ('after1', (), {}), ('before2', (), {}),
                                 ('something2', (), {}), ('after2', (), {})])
Exemplo n.º 7
0
def test_vol_smile():
    replace = Replacer()
    mock_spx = Index('MA890', AssetClass.Equity, 'SPX')
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq)
    actual = tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.FORWARD, '5d')
    assert_series_equal(pd.Series([5, 1, 2], index=[0.75, 0.25, 0.5]), actual)
    actual = tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.SPOT, '5d')
    assert_series_equal(pd.Series([5, 1, 2], index=[0.75, 0.25, 0.5]), actual)

    market_mock = replace(
        'gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock())
    market_mock.return_value = pd.DataFrame()
    actual = tm.vol_smile(mock_spx, '1m', tm.VolSmileReference.SPOT, '1d')
    assert actual.empty
    market_mock.assert_called_once()
    with pytest.raises(NotImplementedError):
        tm.vol_smile(mock_spx,
                     '1m',
                     tm.VolSmileReference.SPOT,
                     '1d',
                     real_time=True)
    replace.restore()
Exemplo n.º 8
0
def test_basket_price():
    with pytest.raises(MqValueError):
        Basket(['AAPL UW'], [0.1, 0.9], RebalFreq.MONTHLY)

    dates = pd.DatetimeIndex([date(2021, 1, 1), date(2021, 1, 2), date(2021, 1, 3), date(2021, 1, 4), date(2021, 1, 5),
                              date(2021, 1, 6)])
    dates_feb = pd.DatetimeIndex([date(2021, 2, 1), date(2021, 2, 2), date(2021, 2, 3), date(2021, 2, 4),
                                  date(2021, 2, 5), date(2021, 2, 6)])

    replace = Replacer()

    mock_data = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock())
    mock_data.side_effect = [_mock_spot_data(), _mock_spot_data_feb()]

    mock_asset = replace('gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data', Mock())
    mock_asset.return_value = [{'id': 'MA4B66MW5E27U9VBB94', 'bbid': 'AAPL UW'},
                               {'id': 'MA4B66MW5E27UAL9SUX', 'bbid': 'MSFT UW'}]

    a_basket = Basket(['AAPL UW', 'MSFT UW'], [0.1, 0.9], RebalFreq.MONTHLY)
    expected = pd.Series([100.0, 100.1, 100.302, 100.09596, 100.09596, 100.297879], index=dates)
    with DataContext('2021-01-01', '2021-01-06'):
        actual = a_basket.price()
    assert_series_equal(actual, expected)

    expected = pd.Series([100.00, 101.50, 100.62, 98.30, 96.30, 94.80], index=dates_feb)
    with DataContext('2021-02-01', '2021-02-06'):
        actual = a_basket.price()
    assert_series_equal(actual, expected)

    mock_asset = replace('gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data', Mock())
    mock_asset.return_value = [{'id': 'MA4B66MW5E27U9VBB94', 'bbid': 'AAPL UW'}]
    with pytest.raises(MqValueError):
        Basket(['AAPL UW', 'ABC'], [0.1, 0.9], RebalFreq.MONTHLY).price()

    with pytest.raises(NotImplementedError):
        a_basket.price(real_time=True)

    replace.restore()
Exemplo n.º 9
0
def test_basket_average_realized_vol():
    replace = Replacer()

    dates = pd.DatetimeIndex([date(2021, 1, 1), date(2021, 1, 2), date(2021, 1, 3), date(2021, 1, 4), date(2021, 1, 5),
                              date(2021, 1, 6)])
    dates_feb = pd.DatetimeIndex([date(2021, 2, 1), date(2021, 2, 2), date(2021, 2, 3), date(2021, 2, 4),
                                  date(2021, 2, 5), date(2021, 2, 6)])

    mock_data = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock())
    mock_data.side_effect = [_mock_spot_data(), _mock_spot_data_feb()]

    mock_asset = replace('gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data', Mock())
    mock_asset.return_value = [{'id': 'MA4B66MW5E27U9VBB94', 'bbid': 'AAPL UW'},
                               {'id': 'MA4B66MW5E27UAL9SUX', 'bbid': 'MSFT UW'}]

    a_basket = Basket(['AAPL UW', 'MSFT UW'], [0.1, 0.9], RebalFreq.DAILY)

    expected = pd.Series([1.1225, 4.49, 2.245, 2.245], index=dates[2:])
    with DataContext('2021-01-01', '2021-01-06'):
        actual = a_basket.average_realized_volatility('2d')
    assert_series_equal(actual, expected)

    expected = pd.Series([3.304542, 3.174902, 3.174902], index=dates[3:])
    with DataContext('2021-01-01', '2021-01-06'):
        actual = a_basket.average_realized_volatility('3d')
    assert_series_equal(actual, expected)
    mock_data.assert_called_once()

    expected = pd.Series([34.698082, 19.719302, 18.860533], index=dates_feb[3:])
    with DataContext('2021-02-01', '2021-02-06'):
        actual = a_basket.average_realized_volatility('3d')
    assert_series_equal(actual, expected)

    with pytest.raises(NotImplementedError):
        a_basket.average_realized_volatility('2d', real_time=True)

    replace.restore()
Exemplo n.º 10
0
def test_basket_average_implied_vol():
    replace = Replacer()

    dates = pd.DatetimeIndex([date(2021, 1, 1), date(2021, 1, 2), date(2021, 1, 3), date(2021, 1, 4), date(2021, 1, 5),
                              date(2021, 1, 6)])

    x = pd.DataFrame({'impliedVolatility': [30.0, 30.2, 29.8, 30.6, 30.1, 30.0]}, index=dates)
    x['assetId'] = 'MA4B66MW5E27U9VBB94'
    y = pd.DataFrame({'impliedVolatility': [20.0, 20.2, 20.3, 20.6, 21.1, 20.0]}, index=dates)
    y['assetId'] = 'MA4B66MW5E27UAL9SUX'
    implied_vol = x.append(y)
    implied_vol.index.name = 'date'

    mock_spot = replace('gs_quant.timeseries.backtesting.ts.get_historical_and_last_for_measure', Mock())
    mock_spot.side_effect = [implied_vol.rename(columns={'impliedVolatility': 'spot'})]

    mock_data = replace('gs_quant.api.utils.ThreadPoolManager.run_async', Mock())
    mock_data.return_value = [implied_vol]

    mock_asset = replace('gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data', Mock())
    mock_asset.return_value = [{'id': 'MA4B66MW5E27U9VBB94', 'bbid': 'AAPL UW'},
                               {'id': 'MA4B66MW5E27UAL9SUX', 'bbid': 'MSFT UW'}]

    a_basket = Basket(['AAPL UW', 'MSFT UW'], [0.1, 0.9], RebalFreq.DAILY)
    expected = pd.Series([21.0, 21.2, 21.25, 21.6, 22.0, 21.0], index=dates)
    actual = a_basket.average_implied_volatility('6m', VolReference.DELTA_CALL, 50)
    assert_series_equal(actual, expected)

    with pytest.raises(NotImplementedError):
        a_basket.average_implied_volatility('6m', VolReference.DELTA_CALL, 50, real_time=True)

    mock_data.return_value = [pd.DataFrame(), pd.DataFrame()]
    expected = pd.Series(dtype=float)
    actual = a_basket.average_implied_volatility('3m', VolReference.FORWARD, 20)  # no data for this
    assert_series_equal(expected, actual)

    replace.restore()
Exemplo n.º 11
0
def _fwd_term_typical():
    assert DataContext.current_is_set
    data = {
        'tenor': ['1w', '2w', '1y', '2y'],
        'forward': [1, 2, 3, 4]
    }
    out = pd.DataFrame(data=data, index=pd.DatetimeIndex(['2018-01-01'] * 4))

    replace = Replacer()
    market_mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock())
    market_mock.return_value = out

    actual = tm.fwd_term(Index('MA123', AssetClass.Equity, '123'))
    idx = pd.DatetimeIndex(['2018-01-08', '2018-01-15', '2019-01-01', '2020-01-01'], name='expirationDate')
    expected = pd.Series([1, 2, 3, 4], name='forward', index=idx)
    expected = expected.loc[DataContext.current.start_date: DataContext.current.end_date]

    if expected.empty:
        assert actual.empty
    else:
        assert_series_equal(expected, actual)
    market_mock.assert_called_once()
    replace.restore()
    return actual
Exemplo n.º 12
0
def test_currency_to_tdapi_xccy_swap_rate_asset(mocker):
    replace = Replacer()
    mocker.patch.object(GsSession.__class__, 'current',
                        return_value=GsSession.get(Environment.QA, 'client_id', 'secret'))
    mocker.patch.object(GsSession.current, '_get', side_effect=mock_request)
    mocker.patch.object(SecurityMaster, 'get_asset', side_effect=mock_request)
    bbid_mock = replace('gs_quant.timeseries.measures_xccy.Asset.get_identifier', Mock())

    with tm_rates.PricingContext(dt.date.today()):
        cur = [
            {
                "currency_assetId": "MAK1FHKH5P5GJSHH",
                "currency": "JPY",
                "xccy_id": "MAFMW4HJC5TDE51H"
            },
            {
                "currency_assetId": "MA66CZBQJST05XKG",
                "currency": "GBP",
                "xccy_id": "MATDD783JM1C2GGD"
            },
            {
                "currency_assetId": "MAJNQPFGN1EBDHAE",
                "currency": "EUR",
                "xccy_id": "MAW8SAXPSKYA94E2"
            },
        ]
        for c in cur:
            print(c)
            asset = Currency(c.get("currency_assetId"), c.get("currency"))
            bbid_mock.return_value = c.get("currency")
            mqid = _currency_to_tdapi_crosscurrency_swap_rate_asset(asset)
            assert mqid == c.get("xccy_id")

        bbid_mock.return_value = None
        assert _currency_to_tdapi_crosscurrency_swap_rate_asset(asset) == c.get("currency_assetId")
        replace.restore()
Exemplo n.º 13
0
def test_currencypair_to_tdapi_fxo_asset(mocker):
    replace = Replacer()
    mocker.patch.object(GsSession.__class__, 'current',
                        return_value=GsSession.get(Environment.QA, 'client_id', 'secret'))
    mocker.patch.object(GsSession.current, '_get', side_effect=mock_request)
    mocker.patch.object(SecurityMaster, 'get_asset', side_effect=mock_request)
    bbid_mock = replace('gs_quant.timeseries.measures_fx_vol.Asset.get_identifier', Mock())

    with tm_rates.PricingContext(dt.date.today()):
        cur = [
            {
                "currency_assetId": "MAK1FHKH5P5GJSHH",
                "currency": "USDJPY",
                "id": "MAQ7YRZ4P94M9N9C"
            },
            {
                "currency_assetId": "MA66CZBQJST05XKG",
                "currency": "GBPUSD",
                "id": "MAEHA6WVHJ2S3JY9"
            },
            {
                "currency_assetId": "MAJNQPFGN1EBDHAE",
                "currency": "EURUSD",
                "id": "MAT1J37C9ZPMANFP"
            },
        ]
        for c in cur:
            print(c)
            asset = Currency(c.get("currency_assetId"), c.get("currency"))
            bbid_mock.return_value = c.get("currency")
            mqid = _currencypair_to_tdapi_fxo_asset(asset)
            assert mqid == c.get("id")

        bbid_mock.return_value = None
        assert _currencypair_to_tdapi_fxo_asset(asset) == c.get("currency_assetId")
        replace.restore()
Exemplo n.º 14
0
def test_skew():
    replace = Replacer()

    mock_spx = Index('MA890', AssetClass.Equity, 'SPX')
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_eq)
    actual = tm.skew(mock_spx, '1m', tm.SkewReference.DELTA, 25)
    assert_series_equal(
        pd.Series([2.0], index=_index, name='impliedVolatility'), actual)

    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_eq_norm)
    actual = tm.skew(mock_spx, '1m', tm.SkewReference.NORMALIZED, 4)
    assert_series_equal(
        pd.Series([2.0], index=_index, name='impliedVolatility'), actual)

    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_eq_spot)
    actual = tm.skew(mock_spx, '1m', tm.SkewReference.SPOT, 25)
    assert_series_equal(
        pd.Series([2.0], index=_index, name='impliedVolatility'), actual)

    mock = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
                   Mock())
    mock.return_value = pd.DataFrame()
    assert tm.skew(mock_spx, '1m', tm.SkewReference.SPOT, 25).empty

    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_inc)
    with pytest.raises(MqError):
        tm.skew(mock_spx, '1m', tm.SkewReference.DELTA, 25)
    replace.restore()

    with pytest.raises(MqError):
        tm.skew(mock_spx, '1m', None, 25)

    with pytest.raises(MqError):
        tm.skew(mock_spx, '1m', tm.SkewReference.SPOT, 25, real_time=True)
Exemplo n.º 15
0
def test_swaption_vol2_return__empty_data():
    replace = Replacer()
    df = ExtendedSeries()

    replace('gs_quant.timeseries.measures.Asset.get_identifier',
            Mock()).return_value = "GBP"
    replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets',
            Mock(),
            Mock()).return_value = ["MADWG3WHCKNE1DJA", "MAH6JK3TZJJGFQ65"]
    replace('gs_quant.timeseries.measures_rates._range_from_pricing_date',
            Mock(),
            Mock()).return_value = [dt.date(2019, 1, 2),
                                    dt.date(2019, 1, 5)]
    replace('gs_quant.timeseries.measures_rates._market_data_timed',
            Mock()).return_value = df

    actual = tm_rates.swaption_vol(Currency("GBP", name="GBP"))
    assert_series_equal(ExtendedSeries(), actual)
    replace.restore()
Exemplo n.º 16
0
def test_swap_rate():
    replace = Replacer()
    mock_usd = Currency('MA890', 'USD')

    xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock())
    xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='USD', ))]
    identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock())
    identifiers.return_value = {'USD-3m': 'MA123'}
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_curr)
    actual = tm.swap_rate(mock_usd, '1y')
    assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='swapRate'), actual)

    identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock())
    identifiers.return_value = {'USD OIS': 'MA123'}
    actual = tm.swap_rate(mock_usd, '1y', BenchmarkType.OIS)
    assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='swapRate'), actual)

    mock_eur = Currency('MA890', 'EUR')
    xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock())
    xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='EUR', ))]
    identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock())
    identifiers.return_value = {'EUR-6m': 'MA123'}
    actual = tm.swap_rate(mock_eur, '1y')
    assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='swapRate'), actual)

    mock_sek = Currency('MA890', 'SEK')
    xrefs = replace('gs_quant.timeseries.measures.GsAssetApi.get_asset_xrefs', Mock())
    xrefs.return_value = [GsTemporalXRef(dt.date(2019, 1, 1), dt.date(2952, 12, 31), XRef(bbid='SEK', ))]
    identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock())
    identifiers.return_value = {'SEK-6m': 'MA123'}
    actual = tm.swap_rate(mock_sek, '1y')
    assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='swapRate'), actual)

    with pytest.raises(NotImplementedError):
        tm.swap_rate(..., '1y', real_time=True)

    replace.restore()
Exemplo n.º 17
0
def test_swaption_vol_smile2_returns_no_data():
    replace = Replacer()
    df = ExtendedSeries()
    replace('gs_quant.timeseries.measures.Asset.get_identifier',
            Mock()).return_value = "GBP"
    replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets',
            Mock(),
            Mock()).return_value = ["MADWG3WHCKNE1DJA", "MAH6JK3TZJJGFQ65"]
    replace('gs_quant.timeseries.measures_rates._range_from_pricing_date',
            Mock(),
            Mock()).return_value = [dt.date(2020, 1, 2),
                                    dt.date(2020, 1, 2)]
    replace('gs_quant.timeseries.measures_rates._market_data_timed',
            Mock()).return_value = df

    with DataContext('2019-01-01', '2025-01-01'):
        actual = tm_rates.swaption_vol_smile(Currency("GBP", name="GBP"), '3m',
                                             '10y')
    assert_series_equal(ExtendedSeries(), actual)
    replace.restore()
Exemplo n.º 18
0
def test_swaption_swaption_vol_term2_returns_empty():
    replace = Replacer()
    df = ExtendedSeries()
    replace('gs_quant.timeseries.measures.Asset.get_identifier',
            Mock()).return_value = "GBP"
    replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets',
            Mock(),
            Mock()).return_value = ["MADWG3WHCKNE1DJA", "MAH6JK3TZJJGFQ65"]
    replace('gs_quant.timeseries.measures_rates._range_from_pricing_date',
            Mock(),
            Mock()).return_value = [dt.date(2020, 1, 2),
                                    dt.date(2020, 1, 2)]
    replace('gs_quant.timeseries.measures_rates._market_data_timed',
            Mock()).return_value = df

    with DataContext('2019-01-01', '2025-01-01'):
        actual = tm_rates.swaption_vol_term(Currency("GBP", name="GBP"),
                                            tm.SwaptionTenorType.SWAP_MATURITY,
                                            '5y', 0)

    assert_series_equal(ExtendedSeries(), actual, check_names=False)
    replace.restore()
Exemplo n.º 19
0
def test_swaption_swaption_vol_term2_returns_data():
    replace = Replacer()
    df = MarketDataResponseFrame(
        data=dict(expirationTenor=['1m', '6m', '1y'], terminationTenor=['1y', '2y', '3y'], swaptionVol=[1, 2, 3]),
        index=_index * 3)

    replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()).return_value = "GBP"
    replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets', Mock(), Mock()).return_value = [
        "MADWG3WHCKNE1DJA", "MAH6JK3TZJJGFQ65"]
    replace('gs_quant.timeseries.measures_rates._range_from_pricing_date', Mock(), Mock()).return_value = [
        dt.date(2020, 1, 2), dt.date(2020, 1, 2)]
    replace('gs_quant.timeseries.measures_rates._market_data_timed', Mock()).return_value = df

    with DataContext('2019-01-01', '2025-01-01'):
        actual = tm_rates.swaption_vol_term(Currency("GBP", name="GBP"), tm.SwaptionTenorType.SWAP_MATURITY, '5y', 0)
    expected = pd.Series([1, 2, 3], index=pd.to_datetime(['2019-02-01', '2019-07-01', '2020-01-01']))
    assert_series_equal(expected, pd.Series(actual), check_names=False)

    with DataContext('2019-01-01', '2025-01-01'):
        actual = tm_rates.swaption_vol_term(Currency("GBP", name="GBP"), tm.SwaptionTenorType.OPTION_EXPIRY, '5y', 0)
    expected = pd.Series([1, 2, 3], index=pd.to_datetime(['2020-01-01', '2021-01-01', '2021-12-31']))
    assert_series_equal(expected, pd.Series(actual), check_names=False)
    replace.restore()
Exemplo n.º 20
0
def test_swaption_vol_smile2_returns_data():
    replace = Replacer()
    test_data = dict(strikeRelative=["ATM", "ATM+50", "ATM+100"],
                     swaptionVol=[1, 2, 3])
    df = MarketDataResponseFrame(data=test_data, index=_index * 3)

    replace('gs_quant.timeseries.measures.Asset.get_identifier',
            Mock()).return_value = "GBP"
    replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets',
            Mock(),
            Mock()).return_value = ["MADWG3WHCKNE1DJA", "MAH6JK3TZJJGFQ65"]
    replace('gs_quant.timeseries.measures_rates._range_from_pricing_date',
            Mock(),
            Mock()).return_value = [dt.date(2020, 1, 2),
                                    dt.date(2020, 1, 2)]
    replace('gs_quant.timeseries.measures_rates._market_data_timed',
            Mock()).return_value = df

    with DataContext('2019-01-01', '2025-01-01'):
        actual = tm_rates.swaption_vol_smile(Currency("GBP", name="GBP"), '3m',
                                             '10y')
    assert_series_equal(pd.Series([1, 2, 3], index=[0.0, 50.0, 100.0]),
                        pd.Series(actual))
    replace.restore()
Exemplo n.º 21
0
def test_swaption_premium_return_data():
    replace = Replacer()
    test_data = dict(swaptionPremium=[1, 2, 3])
    df = MarketDataResponseFrame(
        data=test_data,
        index=[dt.date(2019, 1, 1),
               dt.date(2019, 1, 2),
               dt.date(2019, 1, 3)])

    replace('gs_quant.timeseries.measures.Asset.get_identifier',
            Mock()).return_value = "GBP"
    replace('gs_quant.timeseries.measures_rates._get_tdapi_rates_assets',
            Mock(), Mock()).return_value = "MADWG3WHCKNE1DJA"
    replace('gs_quant.timeseries.measures_rates._range_from_pricing_date',
            Mock(),
            Mock()).return_value = [dt.date(2019, 1, 2),
                                    dt.date(2019, 1, 5)]
    replace('gs_quant.timeseries.measures_rates._market_data_timed',
            Mock()).return_value = df

    actual = tm_rates.swaption_premium(Currency("GBP", name="GBP"))
    assert_series_equal(
        tm._extract_series_from_df(df, QueryType.SWAPTION_PREMIUM), actual)
    replace.restore()
Exemplo n.º 22
0
def test_ois_fxfwd_xcswap_measures(mocker):
    replace = Replacer()
    dict_fns = {
        "oisXccy": {
            "fn": tm_rates.ois_xccy,
            "queryType": QueryType.OIS_XCCY
        },
        "oisXccyExSpike": {
            "fn": tm_rates.ois_xccy_ex_spike,
            "queryType": QueryType.OIS_XCCY_EX_SPIKE
        },
        "usdOis": {
            "fn": tm_rates.usd_ois,
            "queryType": QueryType.USD_OIS
        },
        "nonUsdOis": {
            "fn": tm_rates.non_usd_ois,
            "queryType": QueryType.NON_USD_OIS
        },
    }
    args = dict(tenor='3y', real_time=False)
    for key in dict_fns:
        fn = dict_fns[key]["fn"]
        mock_jpy = Cross('MAYJPCVVF2RWXCES', 'USD/JPY')
        xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                        Mock())
        xrefs.return_value = 'JPYUSD'
        args['asset'] = mock_jpy
        with pytest.raises(NotImplementedError):
            fn(**args)

        mock_eur = Cross('MAA0NE9QX2ABETG6', 'EUR/USD')
        args['asset'] = mock_eur
        xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                        Mock())
        xrefs.return_value = 'EURUSD'
        with pytest.raises(NotImplementedError):
            fn(..., real_time=True)

        args['tenor'] = '5yr'
        with pytest.raises(MqValueError):
            fn(**args)
        args['tenor'] = '3y'

        test_data = {key: [1, 2, 3]}
        df = MarketDataResponseFrame(data=test_data,
                                     index=[
                                         dt.date(2019, 1, 1),
                                         dt.date(2019, 1, 2),
                                         dt.date(2019, 1, 3)
                                     ])
        identifiers = replace(
            'gs_quant.timeseries.measures_rates._get_tdapi_rates_assets',
            Mock())
        identifiers.return_value = {'MAA9MVX15AJNQCVG'}  # Test on EURUSD only
        replace('gs_quant.timeseries.measures_rates._range_from_pricing_date',
                Mock(), Mock()).return_value = [
                    dt.date(2019, 1, 2),
                    dt.date(2019, 1, 5)
                ]
        replace('gs_quant.timeseries.measures_rates._market_data_timed',
                Mock()).return_value = df

        expected = tm_rates._extract_series_from_df(df,
                                                    dict_fns[key]["queryType"])
        actual = fn(**args)
        assert_series_equal(expected, actual)

        replace.restore()
Exemplo n.º 23
0
def test_currency_to_tdapi_swaption_rate_asset_retuns_throws():
    replace = Replacer()
    replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()).return_value = "ZAR"
    asset = Currency("MA1", "ZAR")

    assert _currency_to_tdapi_swaption_rate_asset(asset) == "MA1"
Exemplo n.º 24
0
def test_inflation_swap_term(mocker):
    replace = Replacer()
    args = dict(forward_tenor='1y',
                pricing_date='0d',
                clearing_house=_ClearingHouse.LCH,
                real_time=False)

    class ObjectView(object):
        def __init__(self, d):
            self.__dict__ = d

    holidays = replace('gs_quant.datetime.GsCalendar.get', Mock(holidays=[]))
    holidays.return_value = ObjectView({'holidays': []})

    bd_calendar = replace(
        'gs_quant.timeseries.measures_inflation._get_custom_bd', Mock())
    bd_calendar.return_value = CustomBusinessDay()
    pricing_date_mock = replace(
        'gs_quant.timeseries.measures_inflation._range_from_pricing_date',
        Mock())
    pricing_date_mock.return_value = [dt.date(2019, 1, 1), dt.date(2019, 1, 1)]

    mock_nok = Currency('MA891', 'PLN')
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'ACU'
    args['asset'] = mock_nok
    with pytest.raises(NotImplementedError):
        tm.inflation_swap_term(**args)

    mock_usd = Currency('MAZ7RWC904JYHYPS', 'USD')
    args['asset'] = mock_usd
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'USD'
    args['real_time'] = True
    with pytest.raises(NotImplementedError):
        tm.inflation_swap_term(**args)
    args['real_time'] = False

    args['forward_tenor'] = '5yr'
    with pytest.raises(MqValueError):
        tm.inflation_swap_term(**args)
    args['forward_tenor'] = '1y'

    bd_mock = replace('gs_quant.data.dataset.Dataset.get_data', Mock())
    bd_mock.return_value = pd.DataFrame(data=dict(date="2020-04-10",
                                                  exchange="NYC",
                                                  description="Good Friday"),
                                        index=[pd.Timestamp('2020-04-10')])

    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'USD'
    identifiers_empty = replace(
        'gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock())
    identifiers_empty.return_value = {}
    with pytest.raises(MqValueError):
        tm.inflation_swap_term(**args)

    identifiers = replace(
        'gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock())
    mock_asset = Currency('USD', name='USD')
    mock_asset.id = 'MAEMPCXQG3T716EX'
    mock_asset.exchange = 'OTC'
    identifiers.return_value = [mock_asset]

    d = {
        'terminationTenor': ['1y', '2y', '3y', '4y'],
        'swapRate': [1, 2, 3, 4],
        'assetId': [
            'MAEMPCXQG3T716EX', 'MAFRSWPAF5QPNTP2', 'MA88BXZ3TCTXTFW1',
            'MAC4KAG9B9ZAZHFT'
        ]
    }

    bd_mock.return_value = pd.DataFrame()
    market_data_mock = replace(
        'gs_quant.timeseries.measures_inflation._get_inflation_swap_data',
        Mock())

    market_data_mock.return_value = pd.DataFrame()
    df = pd.DataFrame(data=d, index=_index * 4)
    actual = tm.inflation_swap_term(**args)
    assert actual.empty

    series_apply_mock = replace(
        'gs_quant.timeseries.measures_inflation.pd.Series.apply', Mock())
    series_apply_mock.return_value = pd.Series([
        dt.date(2022, 3, 30),
        dt.date(2023, 3, 30),
        dt.date(2024, 3, 30),
        dt.date(2025, 3, 30)
    ],
                                               index=df.index)

    market_data_mock.return_value = df
    with DataContext('2019-01-01', '2026-01-01'):
        actual = tm.inflation_swap_term(**args)
    actual.dataset_ids = _test_datasets
    expected = tm.ExtendedSeries([1, 2, 3, 4],
                                 index=[
                                     dt.date(2022, 3, 30),
                                     dt.date(2023, 3, 30),
                                     dt.date(2024, 3, 30),
                                     dt.date(2025, 3, 30)
                                 ])
    expected.dataset_ids = _test_datasets
    assert_series_equal(expected, actual, check_names=False)
    assert actual.dataset_ids == expected.dataset_ids

    args['location'] = PricingLocation.NYC
    with DataContext('2019-01-01', '2026-01-01'):
        tm.inflation_swap_term(**args)

    holidays.return_value = ObjectView({'holidays': ['0d']})
    with pytest.raises(MqValueError):
        tm.inflation_swap_term(**args)

    replace.restore()
Exemplo n.º 25
0
def test_bucketize_price():
    target = {
        '7x24': [27.323461],
        'offpeak': [26.004816],
        'peak': [27.982783],
        '7x8': [26.004816],
        '2x16h': [],
        'monthly': [],
        'CAISO 7x24': [26.518563]
    }

    replace = Replacer()
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_commod)
    mock_pjm = Index('MA001', AssetClass.Commod, 'PJM')
    mock_caiso = Index('MA001', AssetClass.Commod, 'CAISO')
    mock_miso = Index('MA001', AssetClass.Commod, 'MISO')

    with DataContext(datetime.date(2019, 5, 1), datetime.date(2019, 5, 1)):
        bbid_mock = replace(
            'gs_quant.timeseries.measures.Asset.get_identifier', Mock())
        bbid_mock.return_value = 'CAISO'

        actual = tm.bucketize_price(mock_caiso,
                                    'LMP',
                                    'totalPrice',
                                    bucket='7x24')
        assert_series_equal(
            pd.Series(target['CAISO 7x24'],
                      index=[datetime.date(2019, 5, 1)],
                      name='price'), actual)

        bbid_mock.return_value = 'PJM'

        actual = tm.bucketize_price(mock_pjm,
                                    'LMP',
                                    'totalPrice',
                                    bucket='7x24')
        assert_series_equal(
            pd.Series(target['7x24'],
                      index=[datetime.date(2019, 5, 1)],
                      name='price'), actual)

        actual = tm.bucketize_price(mock_pjm,
                                    'LMP',
                                    'totalPrice',
                                    bucket='offpeak')
        assert_series_equal(
            pd.Series(target['offpeak'],
                      index=[datetime.date(2019, 5, 1)],
                      name='price'), actual)

        actual = tm.bucketize_price(mock_pjm,
                                    'LMP',
                                    'totalPrice',
                                    bucket='peak')
        assert_series_equal(
            pd.Series(target['peak'],
                      index=[datetime.date(2019, 5, 1)],
                      name='price'), actual)

        actual = tm.bucketize_price(mock_pjm,
                                    'LMP',
                                    'totalPrice',
                                    bucket='7x8')
        assert_series_equal(
            pd.Series(target['7x8'],
                      index=[datetime.date(2019, 5, 1)],
                      name='price'), actual)

        actual = tm.bucketize_price(mock_pjm,
                                    'LMP',
                                    'totalPrice',
                                    bucket='2x16h')
        assert_series_equal(pd.Series(target['2x16h'], index=[], name='price'),
                            actual)

        actual = tm.bucketize_price(mock_pjm,
                                    'LMP',
                                    'totalPrice',
                                    granularity='m',
                                    bucket='7X24')
        assert_series_equal(
            pd.Series(target['monthly'], index=[], name='price'), actual)

        with pytest.raises(ValueError):
            tm.bucketize_price(mock_pjm, 'LMP', 'totalPrice', bucket='weekday')

        with pytest.raises(ValueError):
            tm.bucketize_price(mock_pjm,
                               'LMP',
                               'totalPrice',
                               granularity='yearly')

    replace.restore()
Exemplo n.º 26
0
def test_fx_vol_measure_legacy(mocker):
    replace = Replacer()
    args = dict(tenor='1m', strike_reference=tm_fxo.VolReference('delta_neutral'), relative_strike=0,
                location=None, legacy_implementation=True)

    mock_gbp = Cross('MA26QSMPX9990G66', 'GBPUSD')
    args['asset'] = mock_gbp
    expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='impliedVolatility')
    expected.dataset_ids = _test_datasets
    mocker.patch.object(tm_rates, 'implied_volatility',
                        return_value=expected)
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)
    replace.restore()

    args['legacy_implementation'] = False
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock())
    xrefs.return_value = None
    with pytest.raises(MqValueError):
        tm_fxo.implied_volatility_fxvol(**args)

    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock())
    xrefs.return_value = 'GBPUSD'
    xrefs = replace('gs_quant.timeseries.measures._cross_stored_direction_helper', Mock())
    xrefs.return_value = 'GBPUSD'
    mocker.patch.object(tm_fxo, 'implied_volatility_new',
                        return_value=expected)
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)

    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock())
    xrefs.return_value = 'USDUSD'
    xrefs = replace('gs_quant.timeseries.measures_fx_vol._cross_stored_direction_helper', Mock())
    xrefs.return_value = 'GBPUSD'
    assets = replace('gs_quant.markets.securities.SecurityMaster.get_asset', Mock())
    assets.return_value = mock_gbp
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)

    args['strike_reference'] = tm_fxo.VolReference('delta_call')
    args['relative_strike'] = 25
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)

    args['strike_reference'] = tm_fxo.VolReference('delta_put')
    args['relative_strike'] = 25
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)

    args['strike_reference'] = tm_fxo.VolReference('spot')
    args['relative_strike'] = 100
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)

    args['strike_reference'] = tm_fxo.VolReference('forward')
    args['relative_strike'] = 100
    actual = tm_fxo.implied_volatility_fxvol(**args)
    assert_series_equal(expected, actual)

    args['strike_reference'] = tm_fxo.VolReference('normalized')
    args['relative_strike'] = 100
    xrefs = replace('gs_quant.timeseries.measures_fx_vol._preprocess_implied_vol_strikes_fx', Mock())
    xrefs.return_value = ['normalized', 0]
    with pytest.raises(MqValueError):
        tm_fxo.implied_volatility_fxvol(**args)

    replace.restore()
Exemplo n.º 27
0
 def test_mock_call_same_strict(self):
     m = Mock()
     m.foo(1, 2, x=3)
     compare(m.mock_calls, m.mock_calls, strict=True)
def test_factor_zscore():
    replace = Replacer()

    # mock getting risk model entity()
    mock = replace('gs_quant.api.gs.risk_models.GsRiskModelApi.get_risk_model',
                   Mock())
    mock.return_value = mock_risk_model_obj

    # mock getting risk model factor entity
    mock = replace(
        'gs_quant.api.gs.risk_models.GsFactorRiskModelApi.get_risk_model_data',
        Mock())
    mock.return_value = mock_risk_model_data

    # mock getting risk model factor entity
    mock = replace(
        'gs_quant.api.gs.risk_models.GsFactorRiskModelApi.get_risk_model_factor_data',
        Mock())
    mock.return_value = mock_risk_model_factor_data

    # mock getting asset gsid
    mock = replace('gs_quant.markets.securities.Asset.get_identifier', Mock())
    mock.return_value = '12345'

    # mock getting risk model dates
    mock = replace(
        'gs_quant.api.gs.risk_models.GsRiskModelApi.get_risk_model_dates',
        Mock())
    mock.return_value = ['2020-01-01', '2020-01-02', '2020-01-03']

    # mock getting risk model data
    mock = replace('gs_quant.models.risk_model.FactorRiskModel.get_data',
                   Mock())
    mock.return_value = {
        'results': [{
            'date': '2020-01-01',
            'assetData': {
                'factorExposure': [{
                    'factor_id': 1.01,
                    'factor_id_1': 1.23
                }]
            }
        }, {
            'date': '2020-01-02',
            'assetData': {
                'factorExposure': [{
                    'factor_id': 1.02,
                    'factor_id_1': 1.23
                }]
            }
        }, {
            'date': '2020-01-03',
            'assetData': {
                'factorExposure': [{
                    'factor_id': 1.03,
                    'factor_id_1': 1.23
                }]
            }
        }]
    }

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2020, 1, 3)):
        actual = mrm.factor_zscore(Stock(id_='id', name='Fake Asset'),
                                   'model_id', 'Factor Name')
        assert all(actual.values == [1.01, 1.02, 1.03])

    with pytest.raises(MqValueError):
        mrm.factor_zscore(Stock(id_='id', name='Fake Asset'), 'model_id',
                          'Wrong Factor Name')
    replace.restore()
Exemplo n.º 29
0
def test_aggregate_factor_support():
    replace = Replacer()

    # mock getting risk model entity()
    mock = replace('gs_quant.api.gs.risk_models.GsRiskModelApi.get_risk_model',
                   Mock())
    mock.return_value = risk_model

    mock = replace('gs_quant.api.gs.reports.GsReportApi.get_report', Mock())
    mock.return_value = factor_risk_report

    # mock getting report factor data
    mock = replace(
        'gs_quant.api.gs.reports.GsReportApi.get_factor_risk_report_results',
        Mock())
    mock.return_value = aggregate_factor_data

    # mock getting risk model dates
    mock = replace(
        'gs_quant.api.gs.risk_models.GsRiskModelApi.get_risk_model_dates',
        Mock())
    mock.return_value = ['2010-01-01']

    # mock getting risk model factor category
    mock = replace(
        'gs_quant.api.gs.risk_models.GsFactorRiskModelApi.get_risk_model_data',
        Mock())
    mock.return_value = {
        'results': [{
            'factorData': [{
                'factorId': 'factor_id',
                'factorCategory': 'Factor Name'
            }]
        }]
    }

    # mock getting risk model factor entity
    mock = replace(
        'gs_quant.api.gs.risk_models.GsFactorRiskModelApi.get_risk_model_factor_data',
        Mock())
    mock.return_value = [{
        'identifier': 'factor_id',
        'type': 'Factor',
        'name': 'Factor Name',
        'factorCategory': 'Factor Name'
    }]

    with DataContext(datetime.date(2020, 11, 23), datetime.date(2020, 11, 25)):
        actual = mr.factor_proportion_of_risk('report_id', 'Factor')
        assert all(actual.values == [1, 2, 3])

    with DataContext(datetime.date(2020, 11, 23), datetime.date(2020, 11, 25)):
        actual = mr.daily_risk('report_id', 'Factor')
        assert all(actual.values == [1, 2, 3])

    with DataContext(datetime.date(2020, 11, 23), datetime.date(2020, 11, 25)):
        actual = mr.annual_risk('report_id', 'Factor')
        assert all(actual.values == [1, 2, 3])

    with pytest.raises(MqValueError):
        mr.daily_risk('report_id', 'Factor Name')

    with pytest.raises(MqValueError):
        mr.annual_risk('report_id', 'Factor Name')
    replace.restore()
Exemplo n.º 30
0
def test_basket_average_realized_corr():
    replace = Replacer()

    dates = pd.DatetimeIndex([
        date(2021, 1, 1),
        date(2021, 1, 2),
        date(2021, 1, 3),
        date(2021, 1, 4),
        date(2021, 1, 5),
        date(2021, 1, 6)
    ])

    mock_data = replace(
        'gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock())
    mock_data.side_effect = [
        _mock_spot_data_identical(),
        _mock_spot_data_corr(),
        _mock_spot_data_identical()
    ]

    mock_asset = replace(
        'gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data',
        Mock())
    mock_asset.return_value = [{
        'id': 'MA4B66MW5E27U9VBB94',
        'bbid': 'AAPL UW'
    }, {
        'id': 'MA4B66MW5E27UAL9SUX',
        'bbid': 'MSFT UW'
    }, {
        'id': 'ID of a dUpLiCaTe AAPL',
        'bbid': 'AAPL UW'
    }]

    a_basket = Basket(['AAPL UW', 'MSFT UW'], [0.1, 0.9], RebalFreq.DAILY)

    # Equal series have correlation of 1
    with DataContext('2021-01-01', '2021-01-06'):
        expected = pd.Series([np.nan, np.nan, 1.0, 1.0, 1.0, 1.0], index=dates)
        result = a_basket.average_realized_correlation('2d')
        assert_series_equal(result, expected)

    mock_asset = replace(
        'gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data',
        Mock())
    mock_asset.return_value = [{
        'id': 'MA4B66MW5E27U9VBB94',
        'bbid': 'AAPL UW'
    }, {
        'id': 'MA4B66MW5E27UAL9SUX',
        'bbid': 'MSFT UW'
    }, {
        'id': 'MA4B66MW5E27UANZH2M',
        'bbid': 'XLP UP'
    }, {
        'id': 'ID of a dUpLiCaTe XLP UP',
        'bbid': 'XLP UP'
    }]

    b_basket = Basket(['AAPL UW', 'MSFT UW', 'XLP UP'], [0.2, 0.3, 0.5],
                      RebalFreq.DAILY)

    # Test with two different series
    with DataContext('2021-01-01', '2021-01-06'):
        result = b_basket.average_realized_correlation('5d')
        expected = pd.Series(
            [np.nan, np.nan, np.nan, np.nan, np.nan, 0.26872959922887607],
            index=dates)
        assert_series_equal(result, expected)

    # Test correct error being thrown
    mock_asset = replace(
        'gs_quant.timeseries.backtesting.GsAssetApi.get_many_assets_data',
        Mock())
    mock_asset.return_value = [{
        'id': 'MA4B66MW5E27U9VBB94',
        'bbid': 'AAPL UW'
    }, {
        'id': 'MA4B66MW5E27UAL9SUX',
        'bbid': 'MSFT UW'
    }, {
        'id': 'MA4B66MW5E27UANZH2M',
        'bbid': 'XLP UP'
    }, {
        'id': 'ID of a DuPlIcAtE MSFT UW',
        'bbid': 'MSFT UW'
    }]

    with pytest.raises(NotImplementedError):
        with DataContext('2021-01-01', '2021-01-09'):
            result = b_basket.average_realized_correlation('5d',
                                                           real_time=True)
    replace.restore()
def test_inflation_swap_rate(mocker):
    replace = Replacer()
    args = dict(swap_tenor='5y',
                index_type='UKRPI',
                clearing_house='LCH',
                forward_tenor='5y',
                real_time=False)

    mock_gbp = Currency('MA26QSMPX9990G66', 'GBP')
    args['asset'] = mock_gbp
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'GBP'

    args['swap_tenor'] = '5yr'
    with pytest.raises(MqValueError):
        tm.inflation_swap_rate(**args)
    args['swap_tenor'] = '5y'

    args['forward_tenor'] = '5yr'
    with pytest.raises(MqValueError):
        tm.inflation_swap_rate(**args)
    args['forward_tenor'] = '5y'

    args['real_time'] = True
    with pytest.raises(NotImplementedError):
        tm.inflation_swap_rate(**args)
    args['real_time'] = False

    args['asset'] = Currency('MA666', 'AED')
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'AED'
    with pytest.raises(NotImplementedError):
        tm.inflation_swap_rate(**args)
    args['asset'] = mock_gbp
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'GBP'

    args['index_type'] = tm.InflationIndexType.TESTCPI
    with pytest.raises(MqValueError):
        tm.inflation_swap_rate(**args)
    args['index_type'] = tm.InflationIndexType.UKRPI

    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'GBP'
    identifiers = replace(
        'gs_quant.timeseries.measures_inflation._get_tdapi_inflation_rates_assets',
        Mock())
    identifiers.return_value = {'MA26QSMPX9990G66'}
    mocker.patch.object(GsDataApi,
                        'get_market_data',
                        return_value=mock_curr(None, None))
    actual = tm.inflation_swap_rate(**args)
    expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='swapRate')
    expected.dataset_ids = _test_datasets
    assert_series_equal(expected, actual)
    assert actual.dataset_ids == _test_datasets

    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'EUR'
    identifiers = replace(
        'gs_quant.timeseries.measures_inflation._get_tdapi_inflation_rates_assets',
        Mock())
    identifiers.return_value = {'MAZBW57ZPS54ET7K'}
    mocker.patch.object(GsDataApi,
                        'get_market_data',
                        return_value=mock_curr(None, None))
    args['asset'] = Currency('MAZBW57ZPS54ET7K', 'EUR')
    args['index_type'] = 'FRCPXTOB'
    actual = tm.inflation_swap_rate(**args)
    expected = tm.ExtendedSeries([1, 2, 3], index=_index * 3, name='swapRate')
    expected.dataset_ids = _test_datasets
    assert_series_equal(expected, actual)
    assert actual.dataset_ids == _test_datasets
    replace.restore()
Exemplo n.º 32
0
def test_fx_vol_measure(mocker):
    replace = Replacer()
    args = dict(
        expiry_tenor='1m',
        strike='ATMF',
        option_type='Put',
        expiration_location=None,
        location=None,
        premium_payment_date=None,
    )

    mock_gbp = Cross('MA26QSMPX9990G66', 'GBPUSD')
    args['asset'] = mock_gbp
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'GBPUSD'

    args['expiry_tenor'] = '1yr'
    with pytest.raises(MqValueError):
        tm_fxo.implied_volatility_new(**args)
    args['expiry_tenor'] = '1m'

    args['real_time'] = True
    with pytest.raises(NotImplementedError):
        tm_fxo.implied_volatility_new(**args)
    args['real_time'] = False

    args['asset'] = Cross('MA666', 'USDAED')
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'AEDUSD'
    with pytest.raises(NotImplementedError):
        tm_fxo.implied_volatility_new(**args)
    args['asset'] = mock_gbp

    args['asset'] = Bond('MA667', 'TEST')
    with pytest.raises(NotImplementedError):
        tm_fxo.implied_volatility_new(**args)
    args['asset'] = mock_gbp

    args['asset'] = Cross('MA667', 'GBPUSD')
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'GBPUSD'
    identifiers = replace(
        'gs_quant.timeseries.measures_fx_vol._get_tdapi_fxo_assets', Mock())
    identifiers.return_value = {'MA7F5P92330NGKAR'}
    mocker.patch.object(GsDataApi,
                        'get_market_data',
                        return_value=mock_curr(None, None))
    actual = tm_fxo.implied_volatility_new(**args)
    expected = tm.ExtendedSeries([1, 2, 3],
                                 index=_index * 3,
                                 name='impliedVolatility')
    expected.dataset_ids = _test_datasets
    assert_series_equal(expected, actual)
    assert actual.dataset_ids == _test_datasets

    args['asset'] = Cross('MA667', 'USDCAD')
    args['location'] = PricingLocation.LDN
    args['premium_payment_date'] = 'Fwd Settle'
    args['expiration_location'] = 'NYC'
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'USDCAD'
    identifiers = replace(
        'gs_quant.timeseries.measures_fx_vol._get_tdapi_fxo_assets', Mock())
    identifiers.return_value = {'MA7F5P92330NGKAR'}
    mocker.patch.object(GsDataApi,
                        'get_market_data',
                        return_value=mock_curr(None, None))
    actual = tm_fxo.implied_volatility_new(**args)
    expected = tm.ExtendedSeries([1, 2, 3],
                                 index=_index * 3,
                                 name='impliedVolatility')
    expected.dataset_ids = _test_datasets
    assert_series_equal(expected, actual)
    assert actual.dataset_ids == _test_datasets

    args['option_type'] = 'Call'
    xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier',
                    Mock())
    xrefs.return_value = 'GBPUSD'
    identifiers = replace(
        'gs_quant.timeseries.measures_fx_vol._get_tdapi_fxo_assets', Mock())
    identifiers.return_value = {'MA7F5P92330NGKAR'}
    mocker.patch.object(GsDataApi,
                        'get_market_data',
                        return_value=mock_curr(None, None))
    actual = tm_fxo.implied_volatility_new(**args)
    expected = tm.ExtendedSeries([1, 2, 3],
                                 index=_index * 3,
                                 name='impliedVolatility')
    expected.dataset_ids = _test_datasets
    assert_series_equal(expected, actual)
    assert actual.dataset_ids == _test_datasets

    replace.restore()
Exemplo n.º 33
0
def test_get_tdapi_fxo_assets(mocker):
    mock_asset_1 = GsAsset(asset_class='FX',
                           id='MAW8SAXPSKYA94E2',
                           type_='Option',
                           name='Test_asset')
    mock_asset_2 = GsAsset(asset_class='FX',
                           id='MATDD783JM1C2GGD',
                           type_='Option',
                           name='Test_asset')

    replace = Replacer()
    assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets',
                     Mock())
    assets.return_value = [mock_asset_1]
    assert 'MAW8SAXPSKYA94E2' == tm_fxo._get_tdapi_fxo_assets()
    replace.restore()

    assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets',
                     Mock())
    assets.return_value = [mock_asset_1, mock_asset_2]
    kwargs = dict(asset_parameters_expiration_date='5y',
                  asset_parameters_call_currency='USD',
                  asset_parameters_put_currency='EUR')
    with pytest.raises(MqValueError):
        tm_fxo._get_tdapi_fxo_assets(**kwargs)
    replace.restore()

    assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets',
                     Mock())
    assets.return_value = []
    kwargs = dict(asset_parameters_expiration_date='5y',
                  asset_parameters_call_currency='USD',
                  asset_parameters_put_currency='EUR')
    with pytest.raises(MqValueError):
        tm_fxo._get_tdapi_fxo_assets(**kwargs)
    replace.restore()

    assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets',
                     Mock())
    assets.return_value = [mock_asset_1, mock_asset_2]
    kwargs = dict()
    assert ['MAW8SAXPSKYA94E2', 'MATDD783JM1C2GGD'
            ] == tm._get_tdapi_crosscurrency_rates_assets(**kwargs)
    replace.restore()

    #   test case will test matching sofr maturity with libor leg and flipping legs to get right asset
    kwargs = dict(Asset_class='FX',
                  type='Option',
                  asset_parameters_call_currency='USD',
                  asset_parameters_put_currency='EUR',
                  asset_parameters_expiration_date='1m',
                  asset_parameters_expiration_time='NYC',
                  asset_parameters_option_type='Put',
                  asset_parameters_premium_payment_date='Fwd Settle',
                  asset_parameters_strike_price_relative='10d',
                  pricing_location='NYC')

    assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets',
                     Mock())
    assets.return_value = [mock_asset_1]
    assert 'MAW8SAXPSKYA94E2' == tm_fxo._get_tdapi_fxo_assets(**kwargs)
    replace.restore()
Exemplo n.º 34
0
def test_normalized_performance():
    idx = pd.date_range('2020-01-02', freq='D', periods=3)
    expected = {
        RiskAumSource.Net:
        pd.Series(data=[1, 1 / 0.8, 1 / 0.6],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Gross:
        pd.Series(data=[1, 1.2, 1.4],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Long:
        pd.Series(data=[1, 1.2, 1.4],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Short:
        pd.Series(data=[1, 1 / 0.8, 1 / 0.6],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Custom_AUM:
        pd.Series(data=[1, 1.1, 1.2],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64')
    }

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
        for k, v in expected.items():
            df = MarketDataResponseFrame(data=ppa_data, dtype="float64")
            replace = Replacer()

            # mock GsPortfolioApi.get_reports()
            mock = replace(
                'gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports',
                Mock())
            mock.return_value = [
                Report.from_dict({
                    'id': 'RP1',
                    'positionSourceType': 'Portfolio',
                    'positionSourceId': 'MP1',
                    'type': 'Portfolio Performance Analytics',
                    'parameters': {
                        'transactionCostModel': 'FIXED'
                    }
                })
            ]

            # mock PerformanceReport.get_many_measures()
            mock = replace(
                'gs_quant.markets.report.PerformanceReport.get_many_measures',
                Mock())
            mock.return_value = df

            # mock PerformanceReport.get_custom_aum()
            mock = replace(
                'gs_quant.api.gs.portfolios.GsPortfolioApi.get_custom_aum',
                Mock())
            mock.return_value = aum

            # mock PerformanceReport.get()
            mock = replace('gs_quant.markets.report.PerformanceReport.get',
                           Mock())
            mock.return_value = PerformanceReport(
                report_id='RP1',
                position_source_type='Portfolio',
                position_source_id='MP1',
                report_type='Portfolio Performance Analytics',
                parameters=ReportParameters(transaction_cost_model='FIXED'))

            actual = mr.normalized_performance('MP1', k.value)
            assert all(actual.values == v.values)
            replace.restore()
Exemplo n.º 35
0
 def test_two_elements(self):
     m = Mock()
     m(x=1)
     assert m.call_args == ((), {'x': 1})
Exemplo n.º 36
0
 def test_mock_call_same(self):
     m = Mock()
     m.foo(1, 2, x=3)
     compare(m.mock_calls, m.mock_calls)
Exemplo n.º 37
0
 def test_non_root_params_not_equal(self):
     m = Mock()
     m.foo(x=1).bar()
     # surprising and annoying (and practically unsolvable :-/):
     assert m.mock_calls[-1] == call.foo(y=2).bar()