Example #1
0
def swap_rate(asset: Asset, swap_tenor: str, benchmark_type: BenchmarkType = None, floating_rate_tenor: str = None,
              forward_tenor: Optional[GENERIC_DATE] = None, clearing_house: _ClearingHouse = None, *,
              source: str = None, real_time: bool = False) -> Series:
    """
    GS end-of-day Fixed-Floating interest rate swap (IRS) curves across major currencies.


    :param asset: asset object loaded from security master
    :param swap_tenor: relative date representation of expiration date e.g. 1m
    :param benchmark_type: benchmark type e.g. LIBOR
    :param floating_rate_tenor: floating index rate
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
    spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """
    df = _get_swap_data(asset=asset, swap_tenor=swap_tenor, benchmark_type=benchmark_type,
                        floating_rate_tenor=floating_rate_tenor, forward_tenor=forward_tenor,
                        clearing_house=clearing_house, source=source,
                        real_time=real_time, query_type=QueryType.SWAP_RATE)

    series = ExtendedSeries() if df.empty else ExtendedSeries(df['swapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #2
0
def crosscurrency_swap_rate(asset: Asset,
                            swap_tenor: str,
                            rateoption_type: str = None,
                            forward_tenor: Optional[GENERIC_DATE] = None,
                            clearing_house: tm_rates._ClearingHouse = None,
                            location: PricingLocation = None,
                            *,
                            source: str = None,
                            real_time: bool = False) -> Series:
    """
    GS end-of-day Zero Coupon CrossCurrency Swap curves across major currencies.

    :param asset: asset object loaded from security master
    :param swap_tenor: relative date representation of expiration date e.g. 1m
    :param rateoption_type: benchmark type e.g. LIBOR
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
            spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param location: Example - "TKO", "LDN", "NYC"
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """

    if asset.get_type().value == AssetType.Cross.value:
        pair = asset.name
        [under, over] = [pair[i:i + 3] for i in range(0, 6, 3)]
        asset1 = SecurityMaster.get_asset(under, AssetIdentifier.BLOOMBERG_ID)
        asset2 = SecurityMaster.get_asset(over, AssetIdentifier.BLOOMBERG_ID)
    elif asset.get_type().value == AssetType.Currency.value:
        asset1 = asset
        asset2 = SecurityMaster.get_asset("USD", AssetIdentifier.BLOOMBERG_ID)
    else:
        raise MqValueError('Asset type not supported ' +
                           asset.get_type().value)

    df = _get_crosscurrency_swap_data(asset1=asset1,
                                      asset2=asset2,
                                      swap_tenor=swap_tenor,
                                      rateoption_type=rateoption_type,
                                      forward_tenor=forward_tenor,
                                      clearing_house=clearing_house,
                                      source=source,
                                      real_time=real_time,
                                      query_type=QueryType.XCCY_SWAP_SPREAD,
                                      location=location)

    series = ExtendedSeries(
        dtype=float) if df.empty else ExtendedSeries(df['xccySwapSpread'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
def fci(country_id: str,
        measure: _FCI_MEASURE = _FCI_MEASURE.FCI,
        *,
        source: str = None,
        real_time: bool = False,
        request_id: Optional[str] = None) -> pd.Series:
    """
    Daily Financial Conditions Index (FCI) for each of the world's large economies and many smaller ones,
    as well as aggregate FCIs for regions.

    :param country_id: id of country/region
    :param measure: FCI metric to retrieve
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :param request_id: server request id
    :return: FCI metric value
    """
    if real_time:
        raise NotImplementedError('real-time FCI data is not available')

    type_ = QueryType(inflection.titleize(measure.value))
    if (measure == _FCI_MEASURE.REAL_FCI
            or measure == _FCI_MEASURE.REAL_TWI_CONTRIBUTION):
        ds = Dataset('FCI')
        df = ds.get_data(geographyId=country_id)
        if (measure == _FCI_MEASURE.REAL_FCI):
            measure = 'realFCI'
        else:
            measure = 'realTWIContribution'
        series = ExtendedSeries(dtype=float) if (
            measure not in df.columns) else ExtendedSeries(df[measure])
        series.dataset_ids = ('FCI', )
        return series

    q = GsDataApi.build_market_data_query([country_id],
                                          query_type=type_,
                                          source=source,
                                          real_time=real_time)
    df = _market_data_timed(q, request_id)
    return _extract_series_from_df(df, type_, True)
Example #4
0
def basis_swap_term_structure(asset: Asset, spread_benchmark_type: BenchmarkType = None, spread_tenor: str = None,
                              reference_benchmark_type: BenchmarkType = None, reference_tenor: str = None,
                              forward_tenor: Optional[GENERIC_DATE] = None,
                              clearing_house: _ClearingHouse = None,
                              pricing_date: Optional[GENERIC_DATE] = None,
                              *, source: str = None, real_time: bool = False, ) -> Series:
    """
    GS end-of-day Floating-Floating interest rate swap (IRS) term structure across major currencies.


    :param asset: asset object loaded from security master
    :param spread_benchmark_type: benchmark type of spread leg on which basis spread is added e.g. LIBOR
    :param spread_tenor: relative date representation of expiration date of spread leg e.g. 1m
    :param reference_benchmark_type: benchmark type of reference leg e.g. LIBOR
    :param reference_tenor: relative date representation of expiration date of reference leg e.g. 1m
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
    spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param pricing_date: YYYY-MM-DD or relative date
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """
    if real_time:
        raise NotImplementedError('realtime basis_swap_rate not implemented')

    currency = CurrencyEnum(asset.get_identifier(AssetIdentifier.BLOOMBERG_ID))
    if currency.value not in ['JPY', 'EUR', 'USD', 'GBP']:
        raise NotImplementedError('Data not available for {} basis swap rates'.format(currency.value))

    clearing_house = _check_clearing_house(clearing_house)

    for benchmark_type in [spread_benchmark_type, reference_benchmark_type]:
        _check_benchmark_type(currency, benchmark_type)

    # default benchmark types
    legs_w_defaults = dict()
    legs_w_defaults['spread'] = _get_swap_leg_defaults(currency, spread_benchmark_type, spread_tenor)
    legs_w_defaults['reference'] = _get_swap_leg_defaults(currency, reference_benchmark_type, reference_tenor)

    for key, leg in legs_w_defaults.items():
        if not re.fullmatch('(\\d+)([bdwmy])', leg['floating_rate_tenor']):
            raise MqValueError('invalid floating rate tenor ' + leg['floating_rate_tenor'] + ' index: ' +
                               leg['benchmark_type'])

    forward_tenor = check_forward_tenor(forward_tenor)

    calendar = legs_w_defaults['spread']['pricing_location'].value
    if pricing_date is not None and pricing_date in list(GsCalendar.get(calendar).holidays):
        raise MqValueError('Specified pricing date is a holiday in {} calendar'.format(calendar))

    csaTerms = currency.value + '-1'

    kwargs = dict(type='BasisSwap', asset_parameters_payer_rate_option=legs_w_defaults['spread']['benchmark_type'],
                  asset_parameters_payer_designated_maturity=legs_w_defaults['spread']['floating_rate_tenor'],
                  asset_parameters_receiver_rate_option=legs_w_defaults['reference']['benchmark_type'],
                  asset_parameters_receiver_designated_maturity=legs_w_defaults['reference']['floating_rate_tenor'],
                  asset_parameters_clearing_house=clearing_house.value, asset_parameters_effective_date=forward_tenor,
                  asset_parameters_notional_currency=currency.name,
                  pricing_location=legs_w_defaults['spread']['pricing_location'].value)

    assets = GsAssetApi.get_many_assets(**kwargs)
    if len(assets) == 0:
        raise MqValueError('Specified arguments did not match any asset in the dataset')
    else:
        rate_mqids = [asset.id for asset in assets]

    asset_string = ''
    for mqid in rate_mqids:
        asset_string = asset_string + ',' + mqid
    _logger.debug('assets returned %s', asset_string)

    _logger.debug('where spread_benchmark_type=%s, spread_tenor=%s,  reference_benchmark_type=%s, '
                  'reference_tenor=%s, forward_tenor=%s, pricing_location=%s ',
                  legs_w_defaults['spread']['benchmark_type'], legs_w_defaults['spread']['floating_rate_tenor'],
                  legs_w_defaults['reference']['benchmark_type'], legs_w_defaults['reference']['floating_rate_tenor'],
                  forward_tenor, legs_w_defaults['spread']['pricing_location'].value)

    start, end = _range_from_pricing_date(calendar, pricing_date)
    with DataContext(start, end):
        where = dict(csaTerms=csaTerms)
        q = GsDataApi.build_market_data_query(rate_mqids, QueryType.BASIS_SWAP_RATE, where=where,
                                              source=source, real_time=real_time)
        _logger.debug('q %s', q)
        df = _market_data_timed(q)

    if df.empty:
        series = ExtendedSeries()
    else:
        latest = df.index.max()
        _logger.info('selected pricing date %s', latest)
        df = df.loc[latest]
        business_day = _get_custom_bd(calendar)
        df = df.assign(expirationDate=df.index + df['terminationTenor'].map(_to_offset) + business_day - business_day)
        df = df.set_index('expirationDate')
        df.sort_index(inplace=True)
        df = df.loc[DataContext.current.start_date: DataContext.current.end_date]
        series = ExtendedSeries() if df.empty else ExtendedSeries(df['basisSwapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #5
0
def basis_swap_spread(asset: Asset, swap_tenor: str = '1y',
                      spread_benchmark_type: BenchmarkType = None, spread_tenor: str = None,
                      reference_benchmark_type: BenchmarkType = None, reference_tenor: str = None,
                      forward_tenor: Optional[GENERIC_DATE] = None, clearing_house: _ClearingHouse = None, *,
                      source: str = None, real_time: bool = False, ) -> Series:
    """
    GS end-of-day Floating-Floating interest rate swap (IRS) curves across major currencies.


    :param asset: asset object loaded from security master
    :param swap_tenor: relative date representation of expiration date e.g. 1m
    :param spread_benchmark_type: benchmark type of spread leg on which basis spread is added e.g. LIBOR
    :param spread_tenor: relative date representation of expiration date of paying leg e.g. 1m
    :param reference_benchmark_type: benchmark type of reference leg e.g. LIBOR
    :param reference_tenor: relative date representation of expiration date of reference leg e.g. 1m
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
    spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """
    if real_time:
        raise NotImplementedError('realtime basis_swap_rate not implemented')

    currency = CurrencyEnum(asset.get_identifier(AssetIdentifier.BLOOMBERG_ID))
    if currency.value not in ['JPY', 'EUR', 'USD', 'GBP']:
        raise NotImplementedError('Data not available for {} basis swap rates'.format(currency.value))

    clearing_house = _check_clearing_house(clearing_house)

    for benchmark_type in [spread_benchmark_type, reference_benchmark_type]:
        _check_benchmark_type(currency, benchmark_type)

    if not (re.fullmatch('(\\d+)([bdwmy])', swap_tenor) or re.fullmatch('(frb[1-9])', forward_tenor)):
        raise MqValueError('invalid swap tenor ' + swap_tenor)

    # default benchmark types
    legs_w_defaults = dict()
    legs_w_defaults['spread'] = _get_swap_leg_defaults(currency, spread_benchmark_type, spread_tenor)
    legs_w_defaults['reference'] = _get_swap_leg_defaults(currency, reference_benchmark_type, reference_tenor)

    for key, leg in legs_w_defaults.items():
        if not re.fullmatch('(\\d+)([bdwmy])', leg['floating_rate_tenor']):
            raise MqValueError('invalid floating rate tenor ' + leg['floating_rate_tenor'] + ' index: ' +
                               leg['benchmark_type'])

    forward_tenor = check_forward_tenor(forward_tenor)
    csaTerms = currency.value + '-1'
    kwargs = dict(type='BasisSwap', asset_parameters_termination_date=swap_tenor,
                  asset_parameters_payer_rate_option=legs_w_defaults['spread']['benchmark_type'],
                  asset_parameters_payer_designated_maturity=legs_w_defaults['spread']['floating_rate_tenor'],
                  asset_parameters_receiver_rate_option=legs_w_defaults['reference']['benchmark_type'],
                  asset_parameters_receiver_designated_maturity=legs_w_defaults['reference']['floating_rate_tenor'],
                  asset_parameters_clearing_house=clearing_house.value, asset_parameters_effective_date=forward_tenor,
                  asset_parameters_notional_currency=currency.name,
                  pricing_location=legs_w_defaults['spread']['pricing_location'].value)

    rate_mqid = _convert_asset_for_mdapi_swap_rates(**kwargs)

    _logger.debug('where asset=%s, swap_tenor=%s, spread_benchmark_type=%s, spread_tenor=%s, '
                  'reference_benchmark_type=%s, reference_tenor=%s, forward_tenor=%s, pricing_location=%s ',
                  rate_mqid, swap_tenor, legs_w_defaults['spread']['benchmark_type'],
                  legs_w_defaults['spread']['floating_rate_tenor'],
                  legs_w_defaults['reference']['benchmark_type'], legs_w_defaults['reference']['floating_rate_tenor'],
                  forward_tenor, legs_w_defaults['spread']['pricing_location'].value)

    where = dict(csaTerms=csaTerms)
    q = GsDataApi.build_market_data_query([rate_mqid], QueryType.BASIS_SWAP_RATE, where=where, source=source,
                                          real_time=real_time)
    _logger.debug('q %s', q)
    df = _market_data_timed(q)

    series = ExtendedSeries() if df.empty else ExtendedSeries(df['basisSwapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #6
0
def basis_swap_term_structure(
    asset: Asset,
    spread_benchmark_type: str = None,
    spread_tenor: str = None,
    reference_benchmark_type: str = None,
    reference_tenor: str = None,
    forward_tenor: Optional[GENERIC_DATE] = None,
    clearing_house: _ClearingHouse = None,
    pricing_date: Optional[GENERIC_DATE] = None,
    *,
    source: str = None,
    real_time: bool = False,
) -> Series:
    """
    GS end-of-day Floating-Floating interest rate swap (IRS) term structure across major currencies.


    :param asset: asset object loaded from security master
    :param spread_benchmark_type: benchmark type of spread leg on which basis spread is added e.g. LIBOR
    :param spread_tenor: relative date representation of expiration date of spread leg e.g. 1m
    :param reference_benchmark_type: benchmark type of reference leg e.g. LIBOR
    :param reference_tenor: relative date representation of expiration date of reference leg e.g. 1m
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
            spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param pricing_date: YYYY-MM-DD or relative date
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """
    if real_time:
        raise NotImplementedError('realtime basis_swap_rate not implemented')

    kwargs = _get_basis_swap_kwargs(
        asset=asset,
        spread_benchmark_type=spread_benchmark_type,
        spread_tenor=spread_tenor,
        reference_benchmark_type=reference_benchmark_type,
        reference_tenor=reference_tenor,
        forward_tenor=forward_tenor,
        clearing_house=clearing_house)

    calendar = kwargs['pricing_location']
    if pricing_date is not None and pricing_date in list(
            GsCalendar.get(calendar).holidays):
        raise MqValueError(
            'Specified pricing date is a holiday in {} calendar'.format(
                calendar))

    rate_mqids = _get_mdapi_rates_assets(**kwargs)

    _logger.debug('assets returned %s', ', '.join(rate_mqids))
    _logger.debug(
        'where spread_benchmark_type=%s, spread_tenor=%s,  reference_benchmark_type=%s, '
        'reference_tenor=%s, forward_tenor=%s, pricing_location=%s ',
        kwargs['asset_parameters_payer_rate_option'],
        kwargs['asset_parameters_payer_designated_maturity'],
        kwargs['asset_parameters_receiver_rate_option'],
        kwargs['asset_parameters_receiver_designated_maturity'],
        kwargs['asset_parameters_effective_date'], kwargs['pricing_location'])
    start, end = _range_from_pricing_date(calendar, pricing_date)
    with DataContext(start, end):
        where = dict(csaTerms=kwargs['asset_parameters_notional_currency'] +
                     '-1')
        q = GsDataApi.build_market_data_query(rate_mqids,
                                              QueryType.BASIS_SWAP_RATE,
                                              where=where,
                                              source=source,
                                              real_time=real_time)
        _logger.debug('q %s', q)
        df = _market_data_timed(q)

    if df.empty:
        series = ExtendedSeries()
    else:
        latest = df.index.max()
        _logger.info('selected pricing date %s', latest)
        df = df.loc[latest]
        business_day = _get_custom_bd(calendar)
        df = df.assign(expirationDate=df.index +
                       df['terminationTenor'].map(_to_offset) + business_day -
                       business_day)
        df = df.set_index('expirationDate')
        df.sort_index(inplace=True)
        df = df.loc[DataContext.current.start_date:DataContext.current.
                    end_date]
        series = ExtendedSeries() if df.empty else ExtendedSeries(
            df['basisSwapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #7
0
def swap_term_structure(asset: Asset,
                        benchmark_type: str = None,
                        floating_rate_tenor: str = None,
                        forward_tenor: Optional[GENERIC_DATE] = None,
                        clearing_house: _ClearingHouse = None,
                        pricing_date: Optional[GENERIC_DATE] = None,
                        *,
                        source: str = None,
                        real_time: bool = False) -> Series:
    """
    GS end-of-day Fixed-Floating interest rate swap (IRS) term structure across major currencies.

    :param asset: asset object loaded from security master
    :param benchmark_type: benchmark type e.g. LIBOR
    :param floating_rate_tenor: floating index rate
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
            spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param pricing_date: YYYY-MM-DD or relative date
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate term structure
    """
    if real_time:
        raise NotImplementedError('realtime swap_rate not implemented')

    currency = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
    currency = CurrencyEnum(currency)
    if currency.value not in ['JPY', 'EUR', 'USD', 'GBP', 'CHF', 'SEK']:
        raise NotImplementedError(
            'Data not available for {} swap rates'.format(currency.value))

    clearing_house = _check_clearing_house(clearing_house)
    benchmark_type = _check_benchmark_type(currency, benchmark_type)
    forward_tenor = _check_forward_tenor(forward_tenor)
    defaults = _get_swap_leg_defaults(currency, benchmark_type,
                                      floating_rate_tenor)

    if not re.fullmatch('(\\d+)([bdwmy])', defaults['floating_rate_tenor']):
        raise MqValueError('invalid floating rate tenor ' +
                           defaults['floating_rate_tenor'] + ' for index: ' +
                           defaults['benchmark_type'])

    calendar = defaults['pricing_location'].value
    if pricing_date is not None and pricing_date in list(
            GsCalendar.get(calendar).holidays):
        raise MqValueError(
            'Specified pricing date is a holiday in {} calendar'.format(
                calendar))

    csaTerms = currency.value + '-1'
    fixed_rate = 'ATM'
    kwargs = dict(
        type='Swap',
        asset_parameters_floating_rate_option=defaults['benchmark_type'],
        asset_parameters_fixed_rate=fixed_rate,
        asset_parameters_clearing_house=clearing_house.value,
        asset_parameters_floating_rate_designated_maturity=defaults[
            'floating_rate_tenor'],
        asset_parameters_effective_date=forward_tenor,
        asset_parameters_notional_currency=currency.name,
        pricing_location=defaults['pricing_location'].value)

    rate_mqids = _get_mdapi_rates_assets(**kwargs)

    _logger.debug('assets returned %s', ', '.join(rate_mqids))
    _logger.debug(
        'where benchmark_type=%s, floating_rate_tenor=%s, forward_tenor=%s, '
        'pricing_location=%s', defaults['benchmark_type'],
        defaults['floating_rate_tenor'], forward_tenor,
        defaults['pricing_location'].value)

    start, end = _range_from_pricing_date(calendar, pricing_date)
    with DataContext(start, end):
        where = dict(csaTerms=csaTerms)
        q = GsDataApi.build_market_data_query(rate_mqids,
                                              QueryType.SWAP_RATE,
                                              where=where,
                                              source=source,
                                              real_time=real_time)
        _logger.debug('q %s', q)
        df = _market_data_timed(q)

    if df.empty:
        series = ExtendedSeries()
    else:
        latest = df.index.max()
        _logger.info('selected pricing date %s', latest)
        df = df.loc[latest]
        business_day = _get_custom_bd(calendar)
        df = df.assign(expirationDate=df.index +
                       df['terminationTenor'].map(_to_offset) + business_day -
                       business_day)
        df = df.set_index('expirationDate')
        df.sort_index(inplace=True)
        df = df.loc[DataContext.current.start_date:DataContext.current.
                    end_date]
        series = ExtendedSeries() if df.empty else ExtendedSeries(
            df['swapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #8
0
def basis_swap_spread(
    asset: Asset,
    swap_tenor: str = '1y',
    spread_benchmark_type: str = None,
    spread_tenor: str = None,
    reference_benchmark_type: str = None,
    reference_tenor: str = None,
    forward_tenor: Optional[GENERIC_DATE] = None,
    clearing_house: _ClearingHouse = None,
    *,
    source: str = None,
    real_time: bool = False,
) -> Series:
    """
    GS end-of-day Floating-Floating interest rate swap (IRS) curves across major currencies.


    :param asset: asset object loaded from security master
    :param swap_tenor: relative date representation of expiration date e.g. 1m
    :param spread_benchmark_type: benchmark type of spread leg on which basis spread is added e.g. LIBOR
    :param spread_tenor: relative date representation of expiration date of paying leg e.g. 1m
    :param reference_benchmark_type: benchmark type of reference leg e.g. LIBOR
    :param reference_tenor: relative date representation of expiration date of reference leg e.g. 1m
    :param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
            spot starting swaps, 'imm1' or 'frb1'
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """
    if real_time:
        raise NotImplementedError('realtime basis_swap_rate not implemented')

    if not (re.fullmatch('(\\d+)([bdwmy])', swap_tenor)
            or re.fullmatch('(frb[1-9])', forward_tenor)):
        raise MqValueError('invalid swap tenor ' + swap_tenor)

    kwargs = _get_basis_swap_kwargs(
        asset=asset,
        spread_benchmark_type=spread_benchmark_type,
        spread_tenor=spread_tenor,
        reference_benchmark_type=reference_benchmark_type,
        reference_tenor=reference_tenor,
        forward_tenor=forward_tenor,
        clearing_house=clearing_house)
    kwargs['asset_parameters_termination_date'] = swap_tenor

    rate_mqid = _get_mdapi_rates_assets(**kwargs)
    _logger.debug(
        'where asset=%s, swap_tenor=%s, spread_benchmark_type=%s, spread_tenor=%s, '
        'reference_benchmark_type=%s, reference_tenor=%s, forward_tenor=%s, pricing_location=%s ',
        rate_mqid, swap_tenor, kwargs['asset_parameters_payer_rate_option'],
        kwargs['asset_parameters_payer_designated_maturity'],
        kwargs['asset_parameters_receiver_rate_option'],
        kwargs['asset_parameters_receiver_designated_maturity'],
        kwargs['asset_parameters_effective_date'], kwargs['pricing_location'])

    where = dict(csaTerms=kwargs['asset_parameters_notional_currency'] + '-1')
    q = GsDataApi.build_market_data_query([rate_mqid],
                                          QueryType.BASIS_SWAP_RATE,
                                          where=where,
                                          source=source,
                                          real_time=real_time)
    _logger.debug('q %s', q)
    df = _market_data_timed(q)

    series = ExtendedSeries() if df.empty else ExtendedSeries(
        df['basisSwapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #9
0
def basis_swap_term_structure(
    asset: Asset,
    spread_benchmark_type: str = None,
    spread_tenor: str = None,
    reference_benchmark_type: str = None,
    reference_tenor: str = None,
    tenor_type: _SwapTenorType = None,
    tenor: Optional[GENERIC_DATE] = None,
    clearing_house: _ClearingHouse = None,
    pricing_date: Optional[GENERIC_DATE] = None,
    *,
    source: str = None,
    real_time: bool = False,
) -> Series:
    """
    GS end-of-day Floating-Floating interest rate swap (IRS) term structure across major currencies.


    :param asset: asset object loaded from security master
    :param spread_benchmark_type: benchmark type of spread leg on which basis spread is added e.g. LIBOR
    :param spread_tenor: relative date representation of expiration date of spread leg e.g. 1m
    :param reference_benchmark_type: benchmark type of reference leg e.g. LIBOR
    :param reference_tenor: relative date representation of expiration date of reference leg e.g. 1m
    :param tenor_type: specify which tenor should be fixed, SWAP_TENOR or FORWARD_TENOR
    :param tenor: absolute / relative date representation of forward starting point or swap maturity
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param pricing_date: YYYY-MM-DD or relative date
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate curve
    """
    if real_time:
        raise NotImplementedError('realtime basis_swap_rate not implemented')
    tenor_type = _check_tenor_type(tenor_type)
    tenor_dict = _check_term_structure_tenor(tenor_type=tenor_type,
                                             tenor=tenor)
    kwargs = _get_basis_swap_kwargs(
        asset=asset,
        spread_benchmark_type=spread_benchmark_type,
        spread_tenor=spread_tenor,
        reference_benchmark_type=reference_benchmark_type,
        reference_tenor=reference_tenor,
        clearing_house=clearing_house)
    kwargs[tenor_dict['tenor_dataset_field']] = tenor_dict['tenor']
    calendar = kwargs['pricing_location']
    if pricing_date is not None and pricing_date in list(
            GsCalendar.get(calendar).holidays):
        raise MqValueError(
            'Specified pricing date is a holiday in {} calendar'.format(
                calendar))

    rate_mqids = _get_mdapi_rates_assets(**kwargs)
    if isinstance(rate_mqids, str):  # single asset returned
        rate_mqids = [rate_mqids]
    _logger.debug('assets returned %s', ', '.join(rate_mqids))
    _logger.debug(
        'where spread_benchmark_type=%s, spread_tenor=%s,  reference_benchmark_type=%s, '
        'reference_tenor=%s, %s=%s, pricing_location=%s ',
        kwargs['asset_parameters_payer_rate_option'],
        kwargs['asset_parameters_payer_designated_maturity'],
        kwargs['asset_parameters_receiver_rate_option'],
        kwargs['asset_parameters_receiver_designated_maturity'],
        kwargs[tenor_dict['tenor_dataset_field']], tenor_dict['tenor'],
        kwargs['pricing_location'])

    where = _get_basis_swap_csa_terms(
        kwargs['asset_parameters_notional_currency'],
        kwargs['asset_parameters_payer_rate_option'],
        kwargs['asset_parameters_receiver_rate_option'])
    start, end = _range_from_pricing_date(calendar, pricing_date)
    with DataContext(start, end):
        q = GsDataApi.build_market_data_query(rate_mqids,
                                              QueryType.BASIS_SWAP_RATE,
                                              where=where,
                                              source=source,
                                              real_time=real_time)
        _logger.debug('q %s', q)
        df = _market_data_timed(q)

    if df.empty:
        series = ExtendedSeries()
    else:
        latest = df.index.max()
        _logger.info('selected pricing date %s', latest)
        df = df.loc[latest]
        biz_day = _get_custom_bd(calendar)
        col_to_plot = tenor_dict['tenor_to_plot']
        if isinstance(df, pd.Series):  # single asset returned
            series = ExtendedSeries(
                pd.Series(df['basisSwapRate'],
                          index=[
                              _get_term_struct_date(df[col_to_plot], latest,
                                                    biz_day)
                          ]))
            series = series.loc[DataContext.current.start_date:DataContext.
                                current.end_date]
        else:
            if col_to_plot == 'effectiveTenor':  # for forward term structure imm date assets
                df = df[~df[col_to_plot].isin(['imm1', 'imm2', 'imm3', 'imm4']
                                              )]
            df['expirationDate'] = df[col_to_plot].apply(_get_term_struct_date,
                                                         args=(latest,
                                                               biz_day))
            df = df.set_index('expirationDate')
            df.sort_index(inplace=True)
            df = df.loc[DataContext.current.start_date:DataContext.current.
                        end_date]
            series = ExtendedSeries() if df.empty else ExtendedSeries(
                df['basisSwapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series
Example #10
0
def swap_term_structure(asset: Asset,
                        benchmark_type: str = None,
                        floating_rate_tenor: str = None,
                        tenor_type: _SwapTenorType = None,
                        tenor: Optional[GENERIC_DATE] = None,
                        clearing_house: _ClearingHouse = None,
                        pricing_date: Optional[GENERIC_DATE] = None,
                        *,
                        source: str = None,
                        real_time: bool = False) -> Series:
    """
    GS end-of-day Fixed-Floating interest rate swap (IRS) term structure across major currencies.

    :param asset: asset object loaded from security master
    :param benchmark_type: benchmark type e.g. LIBOR
    :param floating_rate_tenor: floating index rate
    :param tenor_type: specify which tenor should be fixed, SWAP_TENOR or FORWARD_TENOR
    :param tenor: absolute / relative date representation of forward starting point or swap maturity
    :param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
    :param pricing_date: YYYY-MM-DD or relative date
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return: swap rate term structure
    """
    if real_time:
        raise NotImplementedError('realtime swap_rate not implemented')

    currency = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
    currency = CurrencyEnum(currency)
    if currency.value not in ['JPY', 'EUR', 'USD', 'GBP', 'CHF', 'SEK']:
        raise NotImplementedError(
            'Data not available for {} swap rates'.format(currency.value))

    clearing_house = _check_clearing_house(clearing_house)
    benchmark_type = _check_benchmark_type(currency, benchmark_type)
    tenor_type = _check_tenor_type(tenor_type)
    tenor_dict = _check_term_structure_tenor(tenor_type=tenor_type,
                                             tenor=tenor)
    defaults = _get_swap_leg_defaults(currency, benchmark_type,
                                      floating_rate_tenor)

    if not re.fullmatch('(\\d+)([bdwmy])', defaults['floating_rate_tenor']):
        raise MqValueError('invalid floating rate tenor ' +
                           defaults['floating_rate_tenor'] + ' for index: ' +
                           defaults['benchmark_type'])

    calendar = defaults['pricing_location'].value
    if pricing_date is not None and pricing_date in list(
            GsCalendar.get(calendar).holidays):
        raise MqValueError(
            'Specified pricing date is a holiday in {} calendar'.format(
                calendar))

    fixed_rate = 'ATM'
    kwargs = dict(
        type='Swap',
        asset_parameters_floating_rate_option=defaults['benchmark_type'],
        asset_parameters_fixed_rate=fixed_rate,
        asset_parameters_clearing_house=clearing_house.value,
        asset_parameters_floating_rate_designated_maturity=defaults[
            'floating_rate_tenor'],
        asset_parameters_notional_currency=currency.name,
        pricing_location=defaults['pricing_location'].value)
    kwargs[tenor_dict['tenor_dataset_field']] = tenor_dict['tenor']
    rate_mqids = _get_mdapi_rates_assets(**kwargs)
    if isinstance(rate_mqids, str):
        rate_mqids = [rate_mqids]
    _logger.debug('assets returned %s', ', '.join(rate_mqids))
    _logger.debug(
        'where benchmark_type=%s, floating_rate_tenor=%s, %s=%s, '
        'pricing_location=%s', defaults['benchmark_type'],
        defaults['floating_rate_tenor'], tenor_type.value, tenor_dict['tenor'],
        defaults['pricing_location'].value)
    where = _get_swap_csa_terms(currency.value, defaults['benchmark_type'])
    start, end = _range_from_pricing_date(calendar, pricing_date)
    with DataContext(start, end):
        q = GsDataApi.build_market_data_query(rate_mqids,
                                              QueryType.SWAP_RATE,
                                              where=where,
                                              source=source,
                                              real_time=real_time)
        _logger.debug('q %s', q)
        df = _market_data_timed(q)

    if df.empty:
        series = ExtendedSeries()
    else:
        latest = df.index.max()
        _logger.info('selected pricing date %s', latest)
        df = df.loc[latest]
        biz_day = _get_custom_bd(calendar)
        col_to_plot = tenor_dict['tenor_to_plot']
        if isinstance(df, pd.Series):
            series = ExtendedSeries(
                pd.Series(df['swapRate'],
                          index=[
                              _get_term_struct_date(df[col_to_plot], latest,
                                                    biz_day)
                          ]))
            series = series.loc[DataContext.current.start_date:DataContext.
                                current.end_date]
        else:
            if col_to_plot == 'effectiveTenor':
                df = df[~df[col_to_plot].isin(['imm1', 'imm2', 'imm3', 'imm4']
                                              )]
            df['expirationDate'] = df[col_to_plot].apply(_get_term_struct_date,
                                                         args=(latest,
                                                               biz_day))
            df = df.set_index('expirationDate')
            df.sort_index(inplace=True)
            df = df.loc[DataContext.current.start_date:DataContext.current.
                        end_date]
            series = ExtendedSeries() if df.empty else ExtendedSeries(
                df['swapRate'])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series