コード例 #1
0
 def __resolve_identifier(self, identifier: str) -> Dict:
     response = GsAssetApi.resolve_assets(identifier=[identifier],
                                          fields=['id', 'name'],
                                          limit=1)[identifier]
     if len(response) == 0:
         raise MqValueError(
             f'Asset could not be found using identifier {identifier}')
     self.__name = get(response, '0.name')
     self.__asset_id = get(response, '0.id')
コード例 #2
0
ファイル: baskets.py プロジェクト: EMAinasse/gs-quant
 def __get_gs_asset(identifier: str) -> GsAsset:
     """ Resolves basket identifier during initialization """
     response = GsAssetApi.resolve_assets(identifier=[identifier],
                                          fields=['id'],
                                          limit=1)[identifier]
     if len(response) == 0 or get(response, '0.id') is None:
         raise MqValueError(
             f'Basket could not be found using identifier {identifier}')
     return GsAssetApi.get_asset(get(response, '0.id'))
コード例 #3
0
 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
コード例 #4
0
ファイル: position_set.py プロジェクト: xuover/gs-quant
 def __resolve_identifiers(identifiers: List[str], date: datetime.date) -> Dict:
     response = GsAssetApi.resolve_assets(
         identifier=identifiers,
         fields=['name', 'id'],
         limit=1,
         as_of=date
     )
     try:
         id_map = dict(zip(response.keys(),
                       [dict(id=asset[0]['id'], name=asset[0]['name']) for asset in response.values()]))
     except IndexError:
         unmapped_assets = {_id for _id, asset in response.items() if not asset}
         raise MqValueError(f'Error in resolving the following identifiers: {unmapped_assets}')
     return id_map
コード例 #5
0
ファイル: entity.py プロジェクト: maxpayne84/gs-quant
 def get_thematic_beta(self,
                       basket_identifier: str,
                       start: dt.date = DateLimit.LOW_LIMIT.value,
                       end: dt.date = dt.date.today()) -> pd.DataFrame:
     if not self.positioned_entity_type == EntityType.ASSET:
         raise NotImplementedError
     response = GsAssetApi.resolve_assets(identifier=[basket_identifier],
                                          fields=['id', 'type'], limit=1)[basket_identifier]
     _id, _type = get(response, '0.id'), get(response, '0.type')
     if len(response) == 0 or _id is None:
         raise MqValueError(f'Basket could not be found using identifier {basket_identifier}.')
     if _type not in BasketType.to_list():
         raise MqValueError(f'Asset {basket_identifier} of type {_type} is not a Custom or Research Basket.')
     query = DataQuery(where={'assetId': self.id, 'basketId': _id}, start_date=start, end_date=end)
     response = GsDataApi.query_data(query=query, dataset_id=IndicesDatasets.COMPOSITE_THEMATIC_BETAS.value)
     df = []
     for r in response:
         df.append({'date': r['date'], 'assetId': r['assetId'], 'basketId': r['basketId'],
                    'thematicBeta': r['beta']})
     df = pd.DataFrame(df)
     return df.set_index('date')
コード例 #6
0
ファイル: indices_utils.py プロジェクト: skyquant2/gs-quant
def get_flagships_with_assets(
        identifiers: List[str],
        fields: [str] = [],
        basket_type: List[BasketType] = BasketType.to_list(),
        asset_class: List[AssetClass] = [AssetClass.Equity],
        region: List[Region] = None,
        styles: List[Union[CustomBasketStyles, ResearchBasketStyles]] = None,
        as_of: dt.datetime = None) -> pd.DataFrame:
    """
    Retrieve a list of flagship baskets containing specified assets

    :param identifiers: List of asset identifiers
    :param fields: Fields to retrieve in addition to mqid, name, ticker, region, basket type, \
        description, styles, live date, and asset class
    :param basket_type: Basket type(s)
    :param asset_class: Asset class (defaults to Equity)
    :param region: Basket region(s)
    :param styles: Basket style(s)
    :param as_of: Datetime for which to retrieve baskets (defaults to current time)
    :return: flagship baskets containing specified assets

    **Usage**

    Retrieve a list of flagship baskets containing specified assets

    **Examples**

    Retrieve a list of flagship custom baskets containing 'AAPL UW' single stock

    >>> from gs_quant.markets.indices_utils import *
    >>>
    >>> get_flagships_with_assets(identifiers=['AAPL UW'], basket_type=[BasketType.CUSTOM_BASKET])

    **See also**

    :func:`get_flagship_baskets` :func:`get_flagships_performance` :func:`get_flagships_constituents`
    """
    fields = list(
        set(fields).union(
            set([
                'id', 'name', 'ticker', 'region', 'type', 'description',
                'styles', 'liveDate', 'assetClass'
            ])))
    response = GsAssetApi.resolve_assets(identifier=identifiers,
                                         fields=['id'],
                                         limit=1)
    mqids = [get(asset, '0.id') for asset in response.values()]
    query = dict(fields=fields,
                 type=basket_type,
                 asset_class=asset_class,
                 is_pair_basket=[False],
                 flagship=[True],
                 underlying_asset_ids=mqids)
    if region is not None:
        query.update(region=region)
    if styles is not None:
        query.update(styles=styles)
    response = GsAssetApi.get_many_assets_data_scroll(**query,
                                                      as_of=as_of,
                                                      limit=2000,
                                                      scroll='1m')
    return pd.DataFrame(response)
コード例 #7
0
ファイル: hedge.py プロジェクト: maxpayne84/gs-quant
    def to_dict(self):
        # Convert position set to hedgeTarget and notional
        positions_as_dict = []
        for position in self.initial_portfolio.positions:
            pos = {'assetId': position.asset_id}
            if self.initial_portfolio.reference_notional:
                pos['notional'] = position.weight * self.initial_portfolio.reference_notional
            else:
                if position.quantity is None:
                    raise MqValueError(
                        'Position sets without reference notionals must have quantities for positions.'
                    )
                pos['quantity'] = position.quantity
            positions_as_dict.append(pos)
        if self.initial_portfolio.reference_notional is None:
            positions_to_price = []
            for position in self.initial_portfolio.positions:
                positions_to_price.append({
                    'assetId': position.asset_id,
                    'quantity': position.quantity
                })
            payload = {
                'positions': positions_to_price,
                'parameters': {
                    'currency': 'USD',
                    'pricingDate':
                    self.initial_portfolio.date.strftime('%Y-%m-%d'),
                    'assetDataSetId': 'GSEOD'
                }
            }
            try:
                price_results = GsSession.current._post(
                    '/price/positions', payload)
            except Exception as e:
                raise MqValueError(
                    'There was an error pricing your positions. Please try uploading your positions as '
                    f'weights instead: {e}')
            notional = price_results.get('actualNotional')

        # Resolve any assets in the hedge universe, asset constraints, and asset exclusions
        hedge_date = self.initial_portfolio.date
        identifiers = [identifier for identifier in self.universe]
        if self.exclusions is not None and self.exclusions.assets is not None:
            identifiers = identifiers + [
                asset for asset in self.exclusions.assets
            ]
        if self.constraints is not None:
            if self.constraints.assets is not None:
                identifiers = identifiers + [
                    asset.constraint_name for asset in self.constraints.assets
                ]
        resolver = GsAssetApi.resolve_assets(identifier=identifiers,
                                             fields=['id'],
                                             as_of=hedge_date)
        self.universe = [
            resolver.get(asset, [{
                'id': asset
            }])[0].get('id') for asset in self.universe
        ]
        if self.exclusions is not None:
            if self.exclusions.assets is not None:
                self.exclusions.assets = [
                    resolver.get(asset, [{
                        'id': asset
                    }])[0].get('id') for asset in self.exclusions.assets
                ]
        if self.constraints is not None and self.constraints.assets is not None:
            for con in self.constraints.assets:
                if len(resolver.get(con.constraint_name, [])) > 0:
                    con.constraint_name = resolver.get(
                        con.constraint_name)[0].get('id', con.constraint_name)

        # Parse and return dictionary
        observation_start_date = self.observation_start_date or hedge_date - relativedelta(
            years=1)
        as_dict = {
            'hedgeTarget': {
                'positions': positions_as_dict
            },
            'universe': self.universe,
            'notional': notional,
            'observationStartDate':
            observation_start_date.strftime("%Y-%m-%d"),
            'observationEndDate': hedge_date.strftime("%Y-%m-%d"),
            'backtestStartDate': observation_start_date.strftime("%Y-%m-%d"),
            'backtestEndDate': hedge_date.strftime("%Y-%m-%d"),
            'samplingPeriod': self.sampling_period,
            'maxLeverage': self.max_leverage,
            'explodeUniverse': self.explode_universe,
            'excludeTargetAssets': self.exclude_target_assets,
            'excludeHardToBorrowAssets': self.exclude_hard_to_borrow_assets,
            'excludeRestrictedAssets': self.exclude_hard_to_borrow_assets,
            'maxAdvPercentage': self.max_adv_percentage,
            'maxReturnDeviation': self.max_return_deviation,
            'maxWeight': self.max_weight,
            'marketParticipationRate': self.market_participation_rate,
            'useMachineLearning': True,
            'lassoWeight': self.lasso_weight,
            'ridgeWeight': self.ridge_weight
        }

        exclusions_as_dict = self.exclusions.to_dict(
        ) if self.exclusions else {}
        constraints_as_dict = self.constraints.to_dict(
        ) if self.constraints else {}
        if 'classificationConstraints' in exclusions_as_dict or 'classificationConstraints' in constraints_as_dict:
            exclusions = exclusions_as_dict.get('classificationConstraints',
                                                [])
            constraints = constraints_as_dict.get('classificationConstraints',
                                                  [])
            as_dict['classificationConstraints'] = exclusions + constraints
        if 'assetConstraints' in exclusions_as_dict or 'assetConstraints' in constraints_as_dict:
            exclusions = exclusions_as_dict.get('assetConstraints', [])
            constraints = constraints_as_dict.get('assetConstraints', [])
            as_dict['assetConstraints'] = exclusions + constraints
        if 'esgConstraints' in constraints_as_dict:
            as_dict['esgConstraints'] = constraints_as_dict.get(
                'esgConstraints', [])
        if self.percentage_in_cash:
            as_dict['percentageInCash'] = self.percentage_in_cash
        if self.exclude_corporate_actions_types:
            as_dict['excludeCorporateActionTypes'] = [
                x.value for x in self.exclude_corporate_actions_types
            ]
        if self.min_market_cap:
            as_dict['minMarketCap'] = self.min_market_cap
        if self.max_market_cap:
            as_dict['maxMarketCap'] = self.max_market_cap

        return as_dict