Ejemplo n.º 1
0
def test_skew_fx():
    replace = Replacer()
    mock = Cross('MAA0NE9QX2ABETG6', 'USD/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='EURUSD', ))]
    replace('gs_quant.markets.securities.SecurityMaster.get_asset', mock)
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx)
    actual = tm.skew(Cross('MAA0NE9QX2ABETG6', 'USD/EUR'), '1m', None, 25)
    assert_series_equal(pd.Series([2.0], index=_index, name='impliedVolatility'), actual)
    replace.restore()
Ejemplo n.º 2
0
def test_cross_to_fxfwd_xcswp_asset(mocker):
    replace = Replacer()
    mocker.patch.object(GsSession.__class__,
                        'current',
                        return_value=GsSession.get(Environment.DEV,
                                                   '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.Asset.get_identifier',
                        Mock())
    correct_mapping = {
        'EURUSD': {
            "id": 'MA1VJC1E3SZW8E4S',
            "crossID": "MAA9MVX15AJNQCVG"
        },
        'GBPUSD': {
            "id": 'MA3JTR4HSC63H4V6',
            "crossID": "MA58R87SPRMKKE7Z"
        },
        'AUDUSD': {
            "id": 'MAD4VBRWYXFSY1N4',
            "crossID": "MAJTN2XJVF97SYJK"
        },
        'NZDUSD': {
            "id": 'MA1YHQMZVTM3VBWT',
            "crossID": "MANQ8REB1VJ4JFTR"
        },
        'USDSEK': {
            "id": 'MA2APZREBGDMME83',
            "crossID": "MA4ZD5CZGC3Y6JZD"
        },
        'USDNOK': {
            "id": 'MA0K3W6FKH6K1KJE',
            "crossID": "MAZ0P16RPG5P0MVF"
        },
        'USDDKK': {
            "id": 'MA328HZB86DYSWSJ',
            "crossID": "MABCHYGJ1TCBCQE4"
        },
        'USDCAD': {
            "id": 'MAT8JNEE2GN5NES6',
            "crossID": "MAP8G81B2KHTYR07"
        },
        'USDCHF': {
            "id": 'MABNGGTNB9A0TKCG',
            "crossID": "MAMPQHNP1A26RS1C"
        },
        'USDJPY': {
            "id": 'MAMZ9YG8AF3HQ18C',
            "crossID": "MAYJPCVVF2RWXCES"
        },
    }

    with tm.PricingContext(dt.date.today()):
        for cross in correct_mapping:
            asset = Cross(correct_mapping[cross]["crossID"], cross)
            bbid_mock.return_value = cross
            correct_id = tm_rates._cross_to_fxfwd_xcswp_asset(asset)
            assert correct_mapping[cross]["id"] == correct_id
    replace.restore()
Ejemplo n.º 3
0
def test_vol_fx():
    replace = Replacer()

    mock = Cross('MAA0NE9QX2ABETG6', 'USD/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='EURUSD', ))]
    replace('gs_quant.markets.securities.SecurityMaster.get_asset', mock)

    # for different delta strikes
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx)
    actual = tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_CALL, 25)
    assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'), actual)
    actual = tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_PUT, 25)
    assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'), actual)
    actual = tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_NEUTRAL)
    assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'), actual)
    actual = tm.implied_volatility(mock, '1m', tm.VolReference.FORWARD, 100)
    assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'), actual)
    actual = tm.implied_volatility(mock, '1m', tm.VolReference.SPOT, 100)
    assert_series_equal(pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'), actual)
    # NORMALIZED not supported
    with pytest.raises(MqError):
        tm.implied_volatility(mock, '1m', tm.VolReference.DELTA_CALL)
    with pytest.raises(MqError):
        tm.implied_volatility(mock, '1m', tm.VolReference.NORMALIZED, 25)
    with pytest.raises(MqError):
        tm.implied_volatility(mock, '1m', tm.VolReference.SPOT, 25)
    with pytest.raises(MqError):
        tm.implied_volatility(mock, '1m', tm.VolReference.FORWARD, 25)
    replace.restore()
Ejemplo n.º 4
0
def test_vol_fx():
    replace = Replacer()
    # for different delta strikes
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx)
    actual = tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                                   tm.VolReference.DELTA_PUT, 50)
    assert_series_equal(
        pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'),
        actual)
    actual = tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                                   tm.VolReference.DELTA_PUT, 25)
    assert_series_equal(
        pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'),
        actual)
    actual = tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                                   tm.VolReference.FORWARD, 100)
    assert_series_equal(
        pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'),
        actual)
    actual = tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                                   tm.VolReference.SPOT, 100)
    assert_series_equal(
        pd.Series([5, 1, 2], index=_index * 3, name='impliedVolatility'),
        actual)
    # NORMALIZED not supported
    with pytest.raises(MqError):
        tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                              tm.VolReference.NORMALIZED, 25)
    with pytest.raises(MqError):
        tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                              tm.VolReference.SPOT, 25)
    with pytest.raises(MqError):
        tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                              tm.VolReference.FORWARD, 25)
    # triggers error if empty and name does not contain '/'
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_fx_empty)
    with pytest.raises(MqError):
        tm.implied_volatility(Cross('MA123', 'ABCXYZ'), '1m',
                              tm.VolReference.DELTA_CALL, 25)
    # checking if reverse cross data is available
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_fx_empty)
    replace('gs_quant.markets.securities.SecurityMaster.get_asset',
            mock_fx_switch)
    xyz = Cross("MA1889", "XYZ/ABC")
    assert tm.implied_volatility(xyz, '1m', tm.VolReference.DELTA_PUT,
                                 25).empty
    replace.restore()
Ejemplo n.º 5
0
def test_vol_forecast_inverse():
    replace = Replacer()
    get_cross = replace('gs_quant.timeseries.measures.cross_to_usd_based_cross', Mock())
    get_cross.return_value = "MATGYV0J9MPX534Z"
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx)

    mock = Cross("MAYJPCVVF2RWXCES", 'USD/JPY')
    actual = tm.forecast(mock, '3m')
    assert_series_equal(pd.Series([1 / 1.1, 1 / 1.1, 1 / 1.1], index=_index * 3, name='forecast'), actual)
    replace.restore()
Ejemplo n.º 6
0
def test_basis():
    replace = Replacer()
    mock_jpyusd = Cross('MA890', 'USD/JPY')
    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='JPYUSD', ))]
    identifiers = replace('gs_quant.timeseries.measures.GsAssetApi.map_identifiers', Mock())
    identifiers.return_value = {'USD-3m/JPY-3m': 'MA123'}
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_cross)
    actual = tm.basis(mock_jpyusd, '1y')
    assert_series_equal(pd.Series([1, 2, 3], index=_index * 3, name='basis'), actual)
    with pytest.raises(NotImplementedError):
        tm.basis(..., '1y', real_time=True)
    replace.restore()
Ejemplo n.º 7
0
def test_vol_forecast():
    replace = Replacer()
    mock = Cross('MAA0NE9QX2ABETG6', 'USD/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='EURUSD', ))]
    replace('gs_quant.markets.securities.SecurityMaster.get_asset', mock)
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx)
    actual = tm.forecast(mock, '1y')
    assert_series_equal(pd.Series([1.1, 1.1, 1.1], index=_index * 3, name='forecast'), actual)
    actual = tm.forecast(mock, '3m')
    assert_series_equal(pd.Series([1.1, 1.1, 1.1], index=_index * 3, name='forecast'), actual)
    with pytest.raises(NotImplementedError):
        tm.forecast(mock, '1y', real_time=True)
    replace.restore()
Ejemplo n.º 8
0
def test_skew():
    replace = Replacer()
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', mock_fx)
    actual = tm.skew(Cross('MA123', 'ABCXYZ'), '1m', None, 25)
    assert_series_equal(
        pd.Series([2.0], index=_index, name='impliedVolatility'), actual)

    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)
Ejemplo n.º 9
0
def test_forward_price():
    # Tests for US NG assets
    def mock_natgas_forward_price(_cls, _q):
        d = {
            'forwardPrice': [
                2.880,
                2.844,
                2.726,
            ],
            'contract': [
                "F21",
                "G21",
                "H21",
            ]
        }
        df = MarketDataResponseFrame(data=d,
                                     index=pd.to_datetime(
                                         [datetime.date(2019, 1, 2)] * 3))
        df.dataset_ids = _test_datasets
        return df

    replace = Replacer()
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_natgas_forward_price)
    mock = CommodityNaturalGasHub('MA001', 'AGT')

    with DataContext(datetime.date(2019, 1, 2), datetime.date(2019, 1, 2)):
        actual = pd.Series(
            tm.forward_price(mock, price_method='GDD', contract_range='F21'))
        expected = pd.Series([2.880],
                             index=[datetime.date(2019, 1, 2)],
                             name='price')
        assert_series_equal(expected, actual)

    with pytest.raises(MqError):
        tm.forward_price(Cross('MA002', 'USD/EUR'),
                         price_method='GDD',
                         contract_range='F21')

    replace.restore()
Ejemplo n.º 10
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()
Ejemplo n.º 11
0
def mock_fx_switch(_cls, _q, _n):
    replace = Replacer()
    replace('gs_quant.timeseries.measures.GsDataApi.get_market_data',
            mock_fx_empty)
    replace.restore()
    return Cross('MA1889', 'ABC/XYZ')