示例#1
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
示例#2
0
    def get(cls,
            id_value: str,
            id_type: Union[EntityIdentifier, str],
            entity_type: Optional[Union[EntityType, str]] = None):
        id_type = id_type.value if isinstance(id_type, Enum) else id_type

        if entity_type is None:
            entity_type = cls.entity_type()
            endpoint = cls._entity_to_endpoint[entity_type]
        else:
            entity_type = entity_type.value if isinstance(
                entity_type, Enum) else entity_type
            endpoint = cls._entity_to_endpoint[EntityType(entity_type)]

        if entity_type == 'asset':
            from gs_quant.markets.securities import SecurityMaster, AssetIdentifier
            return SecurityMaster.get_asset(id_value,
                                            AssetIdentifier.MARQUEE_ID)

        if id_type == 'MQID':
            result = GsSession.current._get(f'/{endpoint}/{id_value}')
        else:
            result = get(
                GsSession.current._get(
                    f'/{endpoint}?{id_type.lower()}={id_value}'), 'results.0')
        if result:
            return cls._get_entity_from_type(result, EntityType(entity_type))
示例#3
0
def cross_to_basis(asset_id: str) -> str:
    try:
        asset = SecurityMaster.get_asset(asset_id, AssetIdentifier.MARQUEE_ID)
        result = convert_asset_for_rates_data_set(
            asset, RatesConversionType.CROSS_CURRENCY_BASIS)
    except TypeError:
        result = asset_id
    return result
示例#4
0
def currency_to_inflation_benchmark_rate(asset_id: str) -> str:
    try:
        asset = SecurityMaster.get_asset(asset_id, AssetIdentifier.MARQUEE_ID)
        result = convert_asset_for_rates_data_set(
            asset, RatesConversionType.INFLATION_BENCHMARK_RATE)
    except TypeError:
        result = asset_id
    return result
示例#5
0
def _reverse_cross(cross_name):
    if '/' not in cross_name:
        raise MqValueError("Name of cross does not fit expected format")
    else:
        cross = cross_name.split('/')
        new_name = cross[0] + cross[1]
        new_asset = AssetIdentifier.BLOOMBERG_ID
        reverse_cross = SecurityMaster.get_asset(new_name, new_asset)
    return reverse_cross
示例#6
0
def cross_stored_direction_for_fx_vol(
        asset_spec: ASSET_SPEC) -> Union[str, Asset]:
    asset = _asset_from_spec(asset_spec)
    result = asset
    try:
        if asset.asset_class is AssetClass.FX:
            bbid = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
            if bbid is not None:
                cross = _cross_stored_direction_helper(bbid)
                if cross != bbid:
                    cross_asset = SecurityMaster.get_asset(
                        cross, AssetIdentifier.BLOOMBERG_ID)
                    result = cross_asset
    except TypeError:
        result = asset
    return _currencypair_to_tdapi_fxo_asset(result)
示例#7
0
def build_eq_vol_scenario_eod(
    asset_name: str,
    source_dataset: str,
    ref_spot: float = None,
    asset_name_type: AssetIdentifier = AssetIdentifier.REUTERS_ID,
    vol_date: date = date.today()
) -> MarketDataVolShockScenario:

    asset = SecurityMaster.get_asset(asset_name, asset_name_type)
    vol_dataset = Dataset(source_dataset)
    vol_data = vol_dataset.get_data(assetId=[asset.get_marquee_id()],
                                    strikeReference='forward',
                                    startDate=vol_date,
                                    endDate=vol_date)
    asset_ric = asset.get_identifier(AssetIdentifier.REUTERS_ID)
    return MarketDataVolShockScenario.from_dataframe(asset_ric, vol_data,
                                                     ref_spot)
示例#8
0
def build_eq_vol_scenario_intraday(
    asset_name: str,
    source_dataset: str,
    ref_spot: float = None,
    asset_name_type: AssetIdentifier = AssetIdentifier.REUTERS_ID,
    start_time: datetime = datetime.now() - timedelta(hours=1),
    end_time: datetime = datetime.now()
) -> MarketDataVolShockScenario:

    asset = SecurityMaster.get_asset(asset_name, asset_name_type)
    vol_dataset = Dataset(source_dataset)
    vol_data = vol_dataset.get_data(assetId=[asset.get_marquee_id()],
                                    strikeReference='forward',
                                    startTime=start_time,
                                    endTime=end_time)
    asset_ric = asset.get_identifier(AssetIdentifier.REUTERS_ID)
    return MarketDataVolShockScenario.from_dataframe(asset_ric, vol_data,
                                                     ref_spot)
示例#9
0
def implied_volatility_fxvol(asset: Asset,
                             tenor: str,
                             strike_reference: VolReference = None,
                             relative_strike: Real = None,
                             location: Optional[PricingLocation] = None,
                             legacy_implementation: bool = True,
                             *,
                             source: str = None,
                             real_time: bool = False,
                             request_id: Optional[str] = None) -> Series:
    """
    Volatility of an asset implied by observations of market prices.

    :param asset: asset object loaded from security master
    :param tenor: relative date representation of expiration date e.g. 1m
            or absolute calendar strips e.g. 'Cal20', 'F20-G20'
    :param strike_reference: reference for strike level
    :param relative_strike: strike relative to reference
    :param location: location of the data snapshot Example - "HKG", "LDN", "NYC"
    :param legacy_implementation: use FX_IVOl over  FX_VANILLA_OPTIONS_VOLS
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :param request_id: service request id, if any
    :return: implied volatility curve
    """

    if legacy_implementation:
        return (tm.implied_volatility(asset,
                                      tenor,
                                      strike_reference,
                                      relative_strike,
                                      source=source,
                                      real_time=real_time,
                                      request_id=request_id))

    bbid = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
    if bbid is not None:
        cross = _cross_stored_direction_helper(bbid)
        if cross != bbid:
            cross_asset = SecurityMaster.get_asset(
                cross, AssetIdentifier.BLOOMBERG_ID)
        else:
            cross_asset = asset
    else:
        raise MqValueError('Badly setup cross ' + asset.name)

    ref_string, relative_strike = _preprocess_implied_vol_strikes_fx(
        strike_reference, relative_strike)

    if ref_string == 'delta':
        if relative_strike == 0:
            strike = 'DN'
            option_type = OptionType.CALL.value
        else:
            if relative_strike > 0:
                strike = str(relative_strike) + 'D'
                option_type = OptionType.CALL.value
            else:
                strike = str(-relative_strike) + 'D'
                option_type = OptionType.PUT.value
    elif ref_string == VolReference.SPOT.value:
        strike = 'Spot'
        option_type = OptionType.CALL.value
    elif ref_string == VolReference.FORWARD.value:
        strike = 'ATMF'
        option_type = OptionType.CALL.value
    else:
        raise MqValueError(
            'unknown strike_reference and relative_strike combination')

    tenor = _tenor_month_to_year(tenor)
    s = implied_volatility_new(cross_asset,
                               tenor,
                               strike,
                               option_type,
                               location=location)
    return s
示例#10
0
# test API connectivity
request_url = 'https://api.marquee.gs.com/v1/users/self'
request = session.get(url=request_url)
print(request.text)
'''
from datetime import date
from gs_quant.data import Dataset
from gs_quant.markets.securities import SecurityMaster, AssetIdentifier 
from gs_quant.session import GsSession

client_id = ''
client_secret = ''

scopes = GsSession.Scopes.get_default()
GsSession.use(client_id=client_id, client_secret=client_secret, scopes=scopes)

ds = Dataset('USCANFPP_MINI')
print (ds)

gsids = ds.get_coverage()['gsid'].values.tolist()
df = ds.get_data(date(2012, 7, 2), date(2017, 6, 30), gsid=gsids[0:5])

print (df)

for idx, row in df.iterrows():
    marqueeAssetId = row['assetId']
    asset = SecurityMaster.get_asset(marqueeAssetId, AssetIdentifier.MARQUEE_ID)
    df.loc[df['assetId'] == marqueeAssetId, 'assetName'] = asset.name

print (df)
示例#11
0
print("here")
scopes = GsSession.Scopes.get_default()
GsSession.use(client_id=client_id, client_secret=client_secret, scopes=scopes)

ds = Dataset('USCANFPP_MINI')

gsids = ds.get_coverage()['gsid'].values.tolist()
id_to_names = {}
localDB = []
for gsid in gsids:
    data = ds.get_data(gsid=gsid)
    localDB.append(data)
    if not data.empty:
        id = data['assetId'][0]
        id_to_names[gsid] = (id,
                             SecurityMaster.get_asset(
                                 id, AssetIdentifier.MARQUEE_ID))

company_names = list(map(lambda x: (x[0], x[1].name), id_to_names.values()))


def print_all(conn):
    with conn.cursor() as cur:
        cur.execute("SELECT * FROM names")
        rows = cur.fetchall()
        for row in rows:
            print([str(cell) for cell in row])


def add_name(conn, gsid, id, name):
    with conn.cursor() as cur:
        cur.execute("SELECT * FROM names WHERE name = '{}'".format(name))