def test_vol_swap_strike_matches_no_assets_when_expiry_tenor_is_not_none(): with pytest.raises(MqValueError): replace = Replacer() base = Cross('MA667', 'EURUSD') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'EURUSD' mock_asset_1 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset', parameters={"lastFixingDate": "1y"}) mock_asset_2 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset', parameters={"lastFixingDate": "1y"}) assets = replace( 'gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1, mock_asset_2] tm_fxo.vol_swap_strike(base, "10m", location=PricingLocation.LDN, real_time=False)
def test_get_many_assets(mocker, monkeypatch): marquee_id_1 = 'MQA1234567890' marquee_id_2 = 'MQA4567890123' query = {'id': [marquee_id_1, marquee_id_2]} as_of = dt.datetime.utcnow() inputs = EntityQuery(where=FieldFilterMap(**query), fields=None, asOfTime=as_of, limit=100) mock_response = { 'results': (GsAsset.from_dict({ 'id': marquee_id_1, 'assetClass': 'Equity', 'type': 'Single Stock', 'name': 'Test 1' }), GsAsset.from_dict({ 'id': marquee_id_2, 'assetClass': 'Equity', 'type': 'Single Stock', 'name': 'Test 2' })) } expected_response = (GsAsset(id=marquee_id_1, assetClass='Equity', type='Single Stock', name='Test 1'), GsAsset(id=marquee_id_2, assetClass='Equity', type='Single Stock', name='Test 2')) # mock GsSession mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_post', return_value=mock_response) # run test monkeypatch.delenv(ENABLE_ASSET_CACHING, raising=False) response = GsAssetApi.get_many_assets(id=[marquee_id_1, marquee_id_2], as_of=as_of) GsSession.current._post.assert_called_with('/assets/query', cls=GsAsset, payload=inputs) assert response == expected_response monkeypatch.setenv(ENABLE_ASSET_CACHING, 1) # run 2x with cache on response = GsAssetApi.get_many_assets(id=[marquee_id_1, marquee_id_2], as_of=as_of) assert response == expected_response response = GsAssetApi.get_many_assets(id=[marquee_id_1, marquee_id_2], as_of=as_of) assert response == expected_response
def test_get_tdapi_inflation_rates_assets(mocker): mock_asset_1 = GsAsset(asset_class='Rate', id='MA26QSMPX9990G66', type_='InflationSwap', name='Test_asset') mock_asset_2 = GsAsset(asset_class='Rate', id='MA44SBCHF192S6FR', type_='InflationSwap', name='Test_asset') replace = Replacer() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1] assert 'MA26QSMPX9990G66' == tm._get_tdapi_inflation_rates_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_termination_date='5y', asset_parameters_effective_date='0b') with pytest.raises(MqValueError): tm._get_tdapi_inflation_rates_assets(**kwargs) replace.restore() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [] kwargs = dict(asset_parameters_clearing_house='NONE', pricing_location='LDN') with pytest.raises(MqValueError): tm._get_tdapi_inflation_rates_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 ['MA26QSMPX9990G66', 'MA44SBCHF192S6FR' ] == tm._get_tdapi_inflation_rates_assets(**kwargs) replace.restore() # test case will test matching sofr maturity with libor leg and flipping legs to get right asset kwargs = dict(type='InflationSwap', asset_parameters_termination_date='5y', asset_parameters_index=tm.InflationIndexType.UKRPI, asset_parameters_clearing_house='None', asset_parameters_effective_date='5y', asset_parameters_notional_currency='GBP', pricing_location='LDN') assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1] assert 'MA26QSMPX9990G66' == tm._get_tdapi_inflation_rates_assets(**kwargs) replace.restore()
def test_get_tdapi_crosscurrency_rates_assets(mocker): mock_asset_1 = GsAsset(asset_class='Rate', id='MAW8SAXPSKYA94E2', type_='XccySwapMTM', name='Test_asset') mock_asset_2 = GsAsset(asset_class='Rate', id='MATDD783JM1C2GGD', type_='XccySwapMTM', 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._get_tdapi_crosscurrency_rates_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_termination_date='5y', asset_parameters_effective_date='0b') with pytest.raises(MqValueError): tm._get_tdapi_crosscurrency_rates_assets(**kwargs) replace.restore() assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [] kwargs = dict(asset_parameters_clearing_house='NONE', asset_parameters_payer_rate_option="EUR-EURIBOR-TELERATE", asset_parameters_payer_currency='EUR', asset_parameters_payer_designated_maturity='3m', asset_parameters_receiver_rate_option="USD-LIBOR-BBA", asset_parameters_receiver_currency='USD', asset_parameters_receiver_designated_maturity='3m', pricing_location='LDN') with pytest.raises(MqValueError): tm._get_tdapi_crosscurrency_rates_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(type='XccySwapMTM', asset_parameters_termination_date='5y', asset_parameters_payer_rate_option="EUR-EURIBOR-TELERATE", asset_parameters_payer_currency="EUR", asset_parameters_payer_designated_maturity='3m', asset_parameters_receiver_rate_option="USD-LIBOR-BBA", asset_parameters_receiver_currency="USD", asset_parameters_receiver_designated_maturity='3m', asset_parameters_clearing_house='None', asset_parameters_effective_date='5y', pricing_location='LDN') assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1] assert 'MAW8SAXPSKYA94E2' == tm._get_tdapi_crosscurrency_rates_assets(**kwargs) replace.restore()
def test_get_tdapi_fxo_assets(): 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()
def test_rebalance_raises_exception(mocker): # construct inputs index_marquee_id = 'MQIDIndex' asset1_marquee_id = 'MQIDAsset1' asset2_marquee_id = 'MQIDAsset2' position_set = [{'assetId': asset1_marquee_id, 'quantity': 100}, {'assetId': asset2_marquee_id, 'quantity': 200}] publish_parameters = PublishParameters(False, False, False) pricing_parameters = IndicesPriceParameters() pricing_parameters.initialPrice = 100 parameters = { 'publishParameters': publish_parameters, 'pricingParameters': pricing_parameters, 'positionSet': position_set} inputs = IndicesRebalanceInputs(parameters) # mock GsSession mock_asset = GsAsset('Equity', AssetType.Custom_Basket, 'Test Basket') mock_response = CustomBasketsResponse('done', 'approvalId', 'reportId', index_marquee_id) mocker.patch.object(ContextMeta, 'current', return_value=GsSession(Environment.QA)) mocker.patch.object(ContextMeta.current, '_get', return_value=mock_asset) mocker.patch.object(ContextMeta.current, '_post', return_value=mock_response) # run test index = GsIndexApi() with pytest.raises(Exception): response = index.rebalance(inputs) print(response)
def __init__(self, gs_asset: GsAsset = None, **kwargs): self.__error_messages = None if gs_asset: if gs_asset.type.value not in BasketType.to_list(): raise MqValueError( f'Failed to initialize. Asset {gs_asset.id} is not a basket' ) self.__id = gs_asset.id self.__initial_entitlements = gs_asset.entitlements asset_entity: Dict = json.loads( json.dumps(gs_asset.as_dict(), cls=JSONEncoder)) Asset.__init__(self, gs_asset.id, gs_asset.asset_class, gs_asset.name, exchange=gs_asset.exchange, currency=gs_asset.currency, entity=asset_entity) PositionedEntity.__init__(self, gs_asset.id, EntityType.ASSET) self.__populate_current_attributes_for_existing_basket(gs_asset) else: self.__populate_default_attributes_for_new_basket(**kwargs) self.__error_messages = set([]) if get(kwargs, '_finish_init', False): self.__finish_initialization()
def __init__(self, identifier: str = None, gs_asset: GsAsset = None): if identifier: gs_asset = self.__get_gs_asset(identifier) if gs_asset: if gs_asset.type.value not in BasketTypes.to_list(): raise MqValueError( f'Failed to initialize. Asset {gs_asset.id} of type {gs_asset.type.value} \ is not a basket') self.__id = gs_asset.id asset_entity: Dict = json.loads( json.dumps(gs_asset.as_dict(), cls=JSONEncoder)) asset_parameters = get(asset_entity, 'parameters', {}) Asset.__init__(self, gs_asset.id, gs_asset.asset_class, gs_asset.name, exchange=gs_asset.exchange, currency=gs_asset.currency, parameters=AssetParameters(**asset_parameters), entity=asset_entity, entitlements=gs_asset.entitlements) PositionedEntity.__init__(self, gs_asset.id, EntityType.ASSET) self.__populate_current_attributes_for_existing_basket(gs_asset) else: self.__raise_initialization_error( 'use currently implemented class functionality')
def test_rebalance(mocker): # construct inputs index_marquee_id = 'MQIDIndex' asset1_marquee_id = 'MQIDAsset1' asset2_marquee_id = 'MQIDAsset2' position_set = [{'assetId': asset1_marquee_id, 'quantity': 100}, {'assetId': asset2_marquee_id, 'quantity': 200}] publish_parameters = PublishParameters(False, False, False) pricing_parameters = IndicesPriceParameters() pricing_parameters.initialPrice = 100 parameters = { 'publishParameters': publish_parameters, 'pricingParameters': pricing_parameters, 'positionSet': position_set} inputs = IndicesRebalanceInputs(parameters) # mock GsSession mock_asset = GsAsset('Equity', AssetType.Custom_Basket, 'Test Basket') mock_response = CustomBasketsResponse('done', 'approvalId', 'reportId', index_marquee_id) mocker.patch.object(ContextMeta, 'current', return_value=GsSession(Environment.QA)) mocker.patch.object(ContextMeta.current, '_post', return_value=mock_response) mocker.patch.object(GsAssetApi, 'get_asset', return_value=mock_asset) # run test index = GsIndexApi(index_marquee_id) response = index.rebalance(inputs) ContextMeta.current._post.assert_called_with("/indices/{id}/rebalance".format(id=index_marquee_id), payload=inputs, cls=CustomBasketsResponse) assert response == mock_response
def __get_gs_asset(self, identifier: str) -> GsAsset: response = GsAssetApi.resolve_assets(identifier=[identifier], limit=1)[identifier] gs_asset = None if len(response) == 0 else GsAsset.from_dict( response[0]) if gs_asset is None: raise MqValueError( f'Basket could not be found using identifier {identifier}') return gs_asset
def test_vol_swap_strike_matches_multiple_assets(): with pytest.raises(MqValueError): replace = Replacer() base = Cross('MA667', 'EURUSD') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'EURUSD' mock_asset_1 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset') assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1, mock_asset_1] tm_fxo.vol_swap_strike(base, None, location=PricingLocation.LDN, real_time=False) replace.restore()
def test_vol_swap_strike_raises_exception(): with pytest.raises(NotImplementedError): mock_asset_1 = GsAsset(asset_class='FX', id='MAW8SAXPSKYA94E2', type_='Option', name='Test_asset') tm_fxo.vol_swap_strike(mock_asset_1, "none", "none", location=PricingLocation.LDN, real_time=True)
def test_vol_swap_strike(): replace = Replacer() base = Cross('MA667', 'EURUSD') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'EURUSD' mock_asset_1 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset', parameters={"lastFixingDate": "1y"}) mock_asset_2 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset', parameters={"lastFixingDate": "2y"}) assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1, mock_asset_2] mock_data = replace('gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) mock_data.return_value = mock_df() actual = tm_fxo.vol_swap_strike(base, "1y", location=PricingLocation.LDN, real_time=False) assert_series_equal(tm_rates._extract_series_from_df(mock_df(), QueryType.STRIKE_VOL), actual) actual = tm_fxo.vol_swap_strike(base, "1y", None, real_time=False) assert_series_equal(tm_rates._extract_series_from_df(mock_df(), QueryType.STRIKE_VOL), actual) replace.restore()
def test_get_asset(mocker): marquee_id = 'MQA1234567890' mock_response = GsAsset(id=marquee_id, assetClass='Equity', type='Single Stock', name='Test Asset') # mock GsSession mocker.patch.object(GsSession.__class__, 'default_value', return_value=GsSession.get(Environment.QA, 'client_id', 'secret')) mocker.patch.object(GsSession.current, '_get', return_value=mock_response) # run test response = GsAssetApi.get_asset(marquee_id) GsSession.current._get.assert_called_with('/assets/{id}'.format(id=marquee_id), cls=GsAsset) assert response == mock_response
def __init__(self, identifier: str = None, gs_asset: GsAsset = None, **kwargs): user_tokens = get(GsUsersApi.get_current_user_info(), 'tokens', []) user_is_internal = 'internal' in user_tokens if identifier: gs_asset = self.__get_gs_asset(identifier) if gs_asset: if gs_asset.type.value not in BasketType.to_list(): raise MqValueError(f'Failed to initialize. Asset {gs_asset.id} is not a basket') self.__id = gs_asset.id asset_entity: Dict = json.loads(json.dumps(gs_asset.as_dict(), cls=JSONEncoder)) Asset.__init__(self, gs_asset.id, gs_asset.asset_class, gs_asset.name, exchange=gs_asset.exchange, currency=gs_asset.currency, entity=asset_entity) PositionedEntity.__init__(self, gs_asset.id, EntityType.ASSET) user_is_admin = any(token in user_tokens for token in get(gs_asset.entitlements, 'admin', [])) self.__populate_current_attributes_for_existing_basket(gs_asset) self.__set_error_messages(user_is_admin, user_is_internal, True) self.__populate_api_attrs = True else: self.__set_error_messages(True, user_is_internal, False) self.__populate_default_attributes_for_new_basket(**kwargs) self.__populate_api_attrs = False
def __gs_asset_to_asset(cls, gs_asset: GsAsset) -> Asset: asset_type = gs_asset.type.value asset_entity: Dict = json.loads( json.dumps(gs_asset.as_dict(), cls=JSONEncoder)) if asset_type in (GsAssetType.Single_Stock.value, ): return Stock(gs_asset.id, gs_asset.name, gs_asset.exchange, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.ETF.value, ): return ETF(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.exchange, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Index.value, GsAssetType.Risk_Premia.value, GsAssetType.Access.value, GsAssetType.Multi_Asset_Allocation.value): return Index(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.exchange, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Custom_Basket.value, GsAssetType.Research_Basket.value): return Basket(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Future.value, ): return Future(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Cross.value, ): return Cross(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Currency.value, ): return Currency(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Rate.value, ): return Rate(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Cash.value, ): return Cash(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.WeatherIndex.value, ): return WeatherIndex(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Swap.value, ): return Swap(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Option.value, ): return Option(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityReferencePrice.value, ): return CommodityReferencePrice(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityNaturalGasHub.value, ): return CommodityNaturalGasHub(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityEUNaturalGasHub.value, ): return CommodityEUNaturalGasHub(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityPowerNode.value, ): return CommodityPowerNode(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityPowerAggregatedNodes.value, ): return CommodityPowerAggregatedNodes(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Bond.value, ): return Bond(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Commodity.value, ): return Commodity(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.FutureMarket.value, ): return FutureMarket(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.FutureContract.value, ): return FutureContract(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) # workaround as casing is being migrated if asset_type == GsAssetType.Cryptocurrency.value: return Cryptocurrency(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) raise TypeError(f'unsupported asset type {asset_type}')
def get_asset(cls, id_value: str, id_type: AssetIdentifier, as_of: Union[dt.date, dt.datetime] = None, exchange_code: ExchangeCode = None, asset_type: AssetType = None, sort_by_rank: bool = False) -> Asset: """ Get an asset by identifier and identifier type :param id_value: identifier value :param id_type: identifier type :param exchange_code: exchange code :param asset_type: asset type :param as_of: As of date for query :param sort_by_rank: whether to sort assets by rank. :return: Asset object or None **Usage** Get asset object using a specified identifier and identifier type. Where the identifiers are temporal (and can change over time), will use the current MarketContext to evaluate based on the specified date. **Examples** Get asset by bloomberg id: >>> gs = SecurityMaster.get_asset("GS UN", AssetIdentifier.BLOOMBERG_ID) Get asset by ticker and exchange code: >>> gs = SecurityMaster.get_asset("GS", AssetIdentifier.TICKER, exchange_code=ExchangeCode.NYSE) Get asset by ticker and asset type: >>> spx = SecurityMaster.get_asset("SPX", AssetIdentifier.TICKER, asset_type=AssetType.INDEX) **See also** :class:`AssetIdentifier` :func:`get_many_assets` """ if not as_of: as_of = PricingContext.current.pricing_date if isinstance(as_of, dt.date): as_of = dt.datetime.combine(as_of, dt.time(0, 0), pytz.utc) if id_type is AssetIdentifier.MARQUEE_ID: gs_asset = GsAssetApi.get_asset(id_value) return cls.__gs_asset_to_asset(gs_asset) query = {id_type.value.lower(): id_value} if exchange_code is not None: query['exchange'] = exchange_code.value if asset_type is not None: query['type'] = [ t.value for t in cls.__asset_type_to_gs_types(asset_type) ] if sort_by_rank: results = GsAssetApi.get_many_assets(as_of=as_of, return_type=dict, order_by=['>rank'], **query) result = get(results, '0') if result: result = GsAsset.from_dict(result) else: results = GsAssetApi.get_many_assets(as_of=as_of, **query) result = next(iter(results), None) if result: return cls.__gs_asset_to_asset(result)
def __gs_asset_to_asset(cls, gs_asset: GsAsset) -> Asset: asset_type = gs_asset.type.value asset_entity: Dict = json.loads( json.dumps(gs_asset.as_dict(), cls=JSONEncoder)) if asset_type in (GsAssetType.Single_Stock.value, ): return Stock(gs_asset.id, gs_asset.name, gs_asset.exchange, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.ETF.value, ): return ETF(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.exchange, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Index.value, GsAssetType.Risk_Premia.value, GsAssetType.Access.value, GsAssetType.Multi_Asset_Allocation.value): return Index(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.exchange, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Custom_Basket.value, GsAssetType.Research_Basket.value): return Basket(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Future.value, ): return Future(gs_asset.id, gs_asset.assetClass, gs_asset.name, gs_asset.currency, entity=asset_entity) if asset_type in (GsAssetType.Cross.value, ): return Cross(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Currency.value, ): return Currency(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Rate.value, ): return Rate(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Cash.value, ): return Cash(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.WeatherIndex.value, ): return WeatherIndex(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Swap.value, ): return Swap(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Option.value, ): return Option(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityReferencePrice.value, ): return CommodityReferencePrice(gs_asset.id, gs_asset.name, entity=asset_entity) # disabled: this asset type would have to be added to target\common.py and the (Prod) Asset Service first! # if asset_type in (GsAssetType.CommodityNaturalGasHub.value,): # return CommodityNaturalGasHub(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityPowerNode.value, ): return CommodityPowerNode(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.CommodityPowerAggregatedNodes.value, ): return CommodityPowerAggregatedNodes(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Bond.value, ): return Bond(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.Commodity.value, ): return Commodity(gs_asset.id, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.FutureMarket.value, ): return FutureMarket(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) if asset_type in (GsAssetType.FutureContract.value, ): return FutureContract(gs_asset.id, gs_asset.assetClass, gs_asset.name, entity=asset_entity) raise TypeError(f'unsupported asset type {asset_type}')
from gs_quant.target.indices import CustomBasketsResponse, CustomBasketRiskParams from gs_quant.target.reports import Report, User as TargetUser # Helper mock value constants asset_1 = {'name': 'asset 1', 'id': 'id1', 'bbid': 'bbid1'} asset_2 = {'name': 'asset 2', 'id': 'id2', 'bbid': 'bbid2'} assets_data = [asset_1, asset_2] base_user = { 'name': 'First Last', 'email': '*****@*****.**', 'company': 'Company A' } cb_response = CustomBasketsResponse('done', 'R1234567890', 'MA1234567890') gs_asset = GsAsset(asset_class=AssetClass.Equity, type_=AssetType.Custom_Basket, name='Test Basket', id_='MA1234567890', entitlements=TargetEntitlements(admin=['guid:user_abc']), xref=XRef(ticker='GSMBXXXX')) initial_price = {'price': 100} mqid = 'MA1234567890' name = 'Test Basket' positions = [ Position('bbid1', asset_id='id1', quantity=100), Position('bbid2', asset_id='id2', quantity=200) ] positions_weighted = positions = [ Position('bbid1', asset_id='id1', weight=0.4), Position('bbid2', asset_id='id2', weight=0.6) ] position_set = PositionSet(positions, divisor=1000) report = Report(mqid,