Пример #1
0
    def _create(self):
        # If a priceables portfolio, try resolving to MQ portfolio
        if self.__priceables:
            self.save()
            self.priceables = None
            return

        # If a positions portfolio, create using MQ API
        port = GsPortfolioApi.create_portfolio(
            portfolio=MQPortfolio(name=self.name,
                                  currency=self.currency,
                                  entitlements=self.entitlements.to_target()))
        PositionedEntity.__init__(self, port.id, EntityType.PORTFOLIO)
        Entity.__init__(self, port.id, EntityType.PORTFOLIO)
        self.__id = port.id
        self._PositionedEntity__entity_type = EntityType.PORTFOLIO
        self.entitlements = Entitlements.from_target(port.entitlements)
        self.currency = Currency(port.currency)

        # If the portfolio contains positions, upload them to the MQ portfolio and schedule reports
        if self.position_sets:
            position_sets = self.position_sets
            self.position_sets = None
            self.update_positions(position_sets, False)
            self._schedule_first_reports(
                [pos_set.date for pos_set in position_sets])
            self.position_sets = None
Пример #2
0
    def from_dict(cls, obj):
        workspace_components = obj['parameters']['components']
        layout = obj['parameters']['layout']
        stack = deque()
        row_layout = ''
        row_layouts = []
        for c in layout[1:]:
            if c == '(':
                stack.append('(')
            elif c == ')':
                stack.pop()
                if len(stack) == 0:
                    row_layouts.append(row_layout[row_layout.index('c'):])
                    row_layout = ''
            row_layout += c

        workspace_rows = [WorkspaceRow(components=Workspace._parse(row_layout, workspace_components))
                          for row_layout in row_layouts]

        component_count = 0
        # The rest of the components not in the layout should be selector components
        selector_components = []
        if component_count < len(workspace_components):
            for i in range(component_count, len(workspace_components)):
                component = workspace_components[i]
                selector_components.append(TYPE_TO_COMPONENT[component['type']].from_dict(component))

        params = obj['parameters']
        tabs = [WorkspaceTab.from_dict(tab) for tab in params.get('tabs', [])]
        return Workspace(name=obj['name'], rows=workspace_rows, selector_components=selector_components,
                         alias=obj.get('alias'), tabs=tabs,
                         entitlements=Entitlements.from_dict(obj.get('entitlements', {})),
                         description=obj.get('description'),
                         disclaimer=params.get('disclaimer'), maintainers=params.get('maintainers'))
def test_set_entitlements(mocker):
    mock_portfolio = TargetPortfolio(id='MP',
                                     currency='USD',
                                     name='Example Port')
    entitlements = Entitlements(view=EntitlementBlock(users=[
        User(user_id='fakeId',
             name='Fake User',
             email='*****@*****.**',
             company='Goldman Sachs')
    ]))

    mocker.patch.object(GsPortfolioApi,
                        'get_portfolio',
                        return_value=mock_portfolio)
    mocker.patch.object(GsPortfolioApi,
                        'get_position_dates',
                        return_value=[
                            dt.date(2020, 1, 2),
                            dt.date(2020, 2, 1),
                            dt.date(2020, 3, 1)
                        ])
    mocker.patch.object(GsPortfolioApi,
                        'get_positions_for_date',
                        return_value=None)
    mocker.patch.object(GsPortfolioApi, 'update_portfolio', return_value='')

    # run test
    pm = PortfolioManager('MP')
    pm.set_entitlements(entitlements)
Пример #4
0
    def get(cls, portfolio_id: str = None, name: str = None, **kwargs):
        if portfolio_id is None and name is None:
            raise MqValueError(
                'Please specify a portfolio ID and/or portfolio name.')

        portfolios = GsPortfolioApi.get_portfolios(
            portfolio_ids=[portfolio_id] if portfolio_id else None,
            portfolio_names=[name] if name else None)
        if len(portfolios) == 0:
            raise ValueError(
                'No portfolios in Marquee match the requested name and/or ID.')
        if len(portfolios) > 1:
            portfolios = {
                'Name': [p.name for p in portfolios],
                'ID': [p.id for p in portfolios],
                'Created Time': [p.created_time for p in portfolios]
            }
            cls._print_dict(portfolios)
            raise ValueError(
                'More than one portfolio matches the requested name and/or ID. To resolve,'
                ' please find the correct portfolio ID below and set it as your portfolio_id.'
            )
        port = portfolios[0]
        return Portfolio(name=port.name,
                         portfolio_id=port.id,
                         currency=port.currency,
                         entitlements=Entitlements.from_target(
                             port.entitlements))
Пример #5
0
 def get_entitlements(self) -> Entitlements:
     if self.positioned_entity_type == EntityType.PORTFOLIO:
         response = GsPortfolioApi.get_portfolio(self.id)
     elif self.positioned_entity_type == EntityType.ASSET:
         response = GsAssetApi.get_asset(self.id)
     else:
         raise NotImplementedError
     return Entitlements.from_target(response.entitlements)
Пример #6
0
 def set_entitlements(self, entitlements: Entitlements):
     """
     Set the entitlements of a portfolio
     :param entitlements: Entitlements object
     """
     entitlements_as_target = entitlements.to_target()
     portfolio_as_target = GsPortfolioApi.get_portfolio(self.__portfolio_id)
     portfolio_as_target.entitlements = entitlements_as_target
     GsPortfolioApi.update_portfolio(portfolio_as_target)
Пример #7
0
    def __init__(self,
                 priceables: Optional[Union[PriceableImpl,
                                            Iterable[PriceableImpl],
                                            dict]] = (),
                 name: Optional[str] = 'Portfolio ' +
                 dt.datetime.today().strftime("%d %b, %Y"),
                 position_sets: Optional[List] = None,
                 currency: Optional[Currency] = Currency.USD,
                 entitlements: Entitlements = None,
                 *,
                 portfolio_id: str = None):
        """
        Creates a portfolio object which can be used to hold instruments

        :param priceables: constructed with an instrument, portfolio, iterable of either, or a dictionary where
            key is name and value is a priceable
        """
        PriceableImpl.__init__(self)
        Entity.__init__(self, portfolio_id, EntityType.PORTFOLIO)
        self.__name = name
        self.__id = portfolio_id
        self.__currency = currency
        self.__need_to_schedule_reports = False
        self.__entitlements = entitlements if entitlements else Entitlements()
        self.__position_sets = position_sets

        # Can't initialize a portfolio with both priceables or position sets
        if priceables and position_sets:
            raise ValueError(
                'Cannot initialize a portfolio with both position sets and priceables. Please pick one.'
            )

        if portfolio_id:
            # Can't add positions to an existing portfolio within the constructor
            if position_sets:
                raise ValueError(
                    'Cannot add positions to an existing portfolio at construction.'
                    'Please initialize the portfolio without the position sets and then update positions using the '
                    'update_positions(position_sets) function.')
            PositionedEntity.__init__(self, portfolio_id, EntityType.PORTFOLIO)

        if isinstance(priceables, dict):
            priceables_list = []
            for name, priceable in priceables.items():
                priceable.name = name
                priceables_list.append(priceable)
            self.priceables = priceables_list
        else:
            self.priceables = priceables
Пример #8
0
def test_from_dict():
    replace = Replacer()
    mock = replace('gs_quant.api.gs.users.GsUsersApi.get_users', Mock())
    mock.return_value = [
        TargetUser.from_dict({
            'id': 'userId',
            'email': '*****@*****.**',
            'name': 'Jane Doe',
            'company': 'Goldman Sachs Group'
        })
    ]
    ent = Entitlements.from_dict({'edit': ['guid:userId', 'role:roleId']})
    replace.restore()
    assert ent.edit.users == [get_fake_user()]
    assert ent.edit.roles == ['roleId']
Пример #9
0
 def __finish_initialization(self):
     """ Fetches remaining data not retrieved during basket initialization """
     if has(self, 'id'):
         if not has(self, '__initial_positions'):
             position_set = GsAssetApi.get_latest_positions(
                 self.id, PositionType.ANY)
             position_set = PositionSet.from_target(position_set)
             self.__position_set = position_set
             self.__divisor = get(position_set, 'divisor')
             self.__initial_positions = set(
                 deepcopy(self.__position_set.positions))
             set_(self.__initial_state, 'divisor', self.__divisor)
             set_(self.__initial_state, 'position_set', self.__position_set)
         if not has(self.__initial_state, 'initial_price'):
             initial_price = GsIndexApi.initial_price(
                 self.id, dt.date.today())
             self.__initial_price = get(initial_price, 'price')
             set_(self.__initial_state, 'initial_price',
                  self.__initial_price)
         if not has(self.__initial_state, 'publish_to_bloomberg'):
             report = get(self, '__latest_create_report',
                          self.__get_latest_create_report())
             self.__publish_to_bloomberg = get(
                 report, 'parameters.publish_to_bloomberg')
             self.__publish_to_factset = get(
                 report, 'parameters.publish_to_factset')
             self.__publish_to_reuters = get(
                 report, 'parameters.publish_to_reuters')
             set_(self.__initial_state, 'publish_to_bloomberg',
                  self.__publish_to_bloomberg)
             set_(self.__initial_state, 'publish_to_factset',
                  self.__publish_to_factset)
             set_(self.__initial_state, 'publish_to_reuters',
                  self.__publish_to_reuters)
         if not has(self, '__entitlements'):
             self.__entitlements = BasketEntitlements.from_target(
                 self.__initial_entitlements)
     self.__set_error_messages()
Пример #10
0
 def get_entitlements(self):
     entitlements_dict = self.get_entity().get('entitlements')
     if entitlements_dict is None:
         raise ValueError('This entity does not have entitlements.')
     return Entitlements.from_dict(entitlements_dict)
Пример #11
0
def test_to_dict():
    ent = Entitlements(edit=EntitlementBlock(users=[get_fake_user()],
                                             groups=[get_fake_group()]))
    as_dict = ent.to_dict()
    assert as_dict == {'edit': ['guid:userId', 'group:groupId']}
Пример #12
0
def test_to_target():
    ent = Entitlements(edit=EntitlementBlock(users=[get_fake_user()],
                                             groups=[get_fake_group()]))
    as_target = ent.to_target()
    assert as_target.edit == ['guid:userId', 'group:groupId']