Esempio n. 1
0
    def test_create_portfolio_with_properties(self):

        _, scope, property_code, _ = self.id_generator.generate_scope_and_code(
            "property_definition",
            scope=TestDataUtilities.tutorials_scope,
            code_prefix="fund-style-",
            annotations=["Portfolio"])

        data_type_id = models.ResourceId("system", "string")

        #   property definition
        property_definition = models.CreatePropertyDefinitionRequest(
            domain="Portfolio",
            scope=TestDataUtilities.tutorials_scope,
            code=property_code,
            value_required=False,
            display_name="Fund Style",
            life_time="Perpetual",
            data_type_id=data_type_id)

        #   create the property definition
        property_definition_result = self.property_definitions_api.create_property_definition(
            create_property_definition_request=property_definition)

        #  property value
        property_value = "Active"
        portfolio_property = models.ModelProperty(
            key=property_definition_result.key,
            value=models.PropertyValue(label_value=property_value))

        _, scope, portfolio_code = self.id_generator.generate_scope_and_code(
            "portfolio",
            scope=TestDataUtilities.tutorials_scope,
            code_prefix="portfolio-")

        #  details of the portfolio to be created
        request = models.CreateTransactionPortfolioRequest(
            display_name=portfolio_code,
            code=portfolio_code,
            base_currency="GBP",

            # set the property value when creating the portfolio
            properties={property_definition_result.key: portfolio_property})

        # create the portfolio
        portfolio = self.transaction_portfolios_api.create_portfolio(
            scope=scope, create_transaction_portfolio_request=request)

        portfolio_code = portfolio.id.code
        self.assertEqual(portfolio_code, request.code)

        portfolio_properties = self.portfolios_api.get_portfolio_properties(
            TestDataUtilities.tutorials_scope, portfolio_code)

        self.assertEqual(len(portfolio_properties.properties), 1)
        self.assertEqual(
            portfolio_properties.properties[
                property_definition_result.key].value.label_value,
            property_value)
    def test_create_portfolio_with_metric_property(self):
        uuid = self.get_guid()
        effective_date = datetime(year=2018, month=1, day=1, tzinfo=pytz.utc)

        # details of property to be created
        metric_property_definition = models.CreatePropertyDefinitionRequest(
            domain="Portfolio",
            scope=TestDataUtilities.tutorials_scope,
            code="fund-NAV-{}".format(uuid),
            display_name="fund NAV",
            life_time="Perpetual",
            value_required=False,
            data_type_id=models.resource_id.ResourceId(
                scope="system", code="currencyAndAmount"))

        # create property definitions
        metric_property_definition_result = self.property_definitions_api.create_property_definition(
            metric_property_definition)

        # create the property values
        metric_property_value_request = models.PropertyValue(
            metric_value=models.MetricValue(value=1100000, unit="GBP"))
        # metric_property_value_request = models.PropertyValue(label_value="Active")

        # Details of the new portfolio to be created, created here with the minimum set of mandatory fields
        create_portfolio_request = models.CreateTransactionPortfolioRequest(
            code="ud-{}".format(uuid),
            display_name="portfolio-{}".format(uuid),
            base_currency="GBP",
            created=effective_date,
            properties={
                metric_property_definition_result.key:
                models.PerpetualProperty(
                    key=metric_property_definition_result.key,
                    value=metric_property_value_request)
            })

        # Create portfolio
        portfolio_result = self.transaction_portfolios_api.create_portfolio(
            scope=TestDataUtilities.tutorials_scope,
            create_transaction_portfolio_request=create_portfolio_request)
        portfolio_properties = self.portfolios_api.get_portfolio_properties(
            scope=TestDataUtilities.tutorials_scope,
            code=portfolio_result.id.code).properties
        metric_property = portfolio_properties[
            metric_property_definition_result.key]

        # Perform assertions on codes, keys, values and units
        self.assertEqual(portfolio_result.id.code,
                         create_portfolio_request.code)
        self.assertEqual(
            list(portfolio_properties.keys())[0],
            metric_property_definition_result.key)
        self.assertEqual(metric_property.value.metric_value.value,
                         metric_property_value_request.metric_value.value)
        self.assertEqual(metric_property.value.metric_value.unit,
                         metric_property_value_request.metric_value.unit)
 def create_portfolio_model(code):
     model = models.CreateTransactionPortfolioRequest(
         display_name=code,
         code=code,
         base_currency="GBP",
         description="Paper transaction portfolio",
         created="2020-02-25T00:00:00Z",
     )
     return model
    def test_create_portfolio_with_label_property(self):
        # Details of property to be created
        uuid = self.get_guid()
        effective_date = datetime(year=2018, month=1, day=1, tzinfo=pytz.utc)

        label_property_definition = models.CreatePropertyDefinitionRequest(
            domain="Portfolio",
            scope=TestDataUtilities.tutorials_scope,
            code="fund-style-{}".format(uuid),
            display_name="fund style",
            life_time="Perpetual",
            value_required=False,
            data_type_id=models.resource_id.ResourceId(scope="system",
                                                       code="string"))

        # create property definition
        label_property_definition_request = self.property_definitions_api.create_property_definition(
            label_property_definition)

        # create property values
        property_value = models.PropertyValue(label_value="Active")

        # Details of new portfolio to be created
        create_portfolio_request = models.CreateTransactionPortfolioRequest(
            code="ud-{}".format(uuid),
            display_name="portfolio-{}".format(uuid),
            base_currency="GBP",
            created=effective_date,
            properties={
                label_property_definition_request.key:
                models.PerpetualProperty(
                    key=label_property_definition_request.key,
                    value=property_value)
            })

        # create portfolio
        portfolio_request = self.transaction_portfolios_api.create_portfolio(
            scope=TestDataUtilities.tutorials_scope,
            create_transaction_portfolio_request=create_portfolio_request)

        # get properties for assertions
        portfolio_properties = self.portfolios_api.get_portfolio_properties(
            scope=TestDataUtilities.tutorials_scope,
            code=portfolio_request.id.code).properties

        label_property = portfolio_properties[
            label_property_definition_request.key]

        # Perform assertions on keys, codes and values
        self.assertEqual(
            list(portfolio_properties.keys())[0],
            label_property_definition_request.key)
        self.assertEqual(portfolio_request.id.code,
                         create_portfolio_request.code)
        self.assertEqual(label_property.value.label_value,
                         property_value.label_value)
Esempio n. 5
0
def create_portfolios_if_not_exist(client, scope, data_frame, required_mapping,
                                   optional_mapping):
    """
    This function creates portfolios

    :param LusidApi client: The LusidApi client to use
    :param str scope: The scope to create the portfolios in
    :param dict mapping: The mapping from the data_frame to LUSID
    :param pandas DataFrame data_frame: The DataFrame containing the portfolio details
    :param datetime created_date: The date from which the portfolios should be effective
    :param str accounting_method: The accounting method of the portfolios
    :return: dict[str: models.Portfolio]: A dict of the created portfolios keyed by the code
    """
    responses = {}

    portfolio_codes_to_check = data_frame[required_mapping['code']].unique()

    # Get all the portfolios currently in the scope
    existing_portfolios_in_scope = client.portfolios.list_portfolios_for_scope(
        scope=scope)
    existing_portfolio_codes = [
        portfolio.id.code for portfolio in existing_portfolios_in_scope.values
    ]

    # Determine which need to be created by excluding those that already exist
    portfolio_codes_to_create = list(
        set(portfolio_codes_to_check) - set(existing_portfolio_codes))

    for code in portfolio_codes_to_create:

        portfolio = data_frame.loc[data_frame[required_mapping['code']] ==
                                   code]

        # Build the request to create the portfolio
        request = models.CreateTransactionPortfolioRequest(
            display_name=portfolio[required_mapping['display_name']].values[0],
            code=make_code_lusid_friendly(code),
            created=portfolio[required_mapping['created']].values[0],
            base_currency=portfolio[
                required_mapping['base_currency']].values[0])

        for lusid_field, column_name in optional_mapping.items():

            if column_name is not None:
                setattr(request, lusid_field, portfolio[column_name].values[0])

        # Call LUSID to create the portfolio
        response = client.transaction_portfolios.create_portfolio(
            scope=scope, create_request=request)

        responses[code] = response

    return responses
Esempio n. 6
0
def create_portfolios(api_factory, scopes, code, currency):

    """
    This function creates a portfolio in multiple scopes. 
    
    param (lusid.utilities.ClientApiFactory) api_factory: The LUSID api factory to use
    param (list[str]) scopes: The scopes to create the portfolio in
    param (str) code: The code for the portfolio
    param (str) currency: The base/reporting currency of the portfolio
    
    return (list[lusid.models.createportfolioresponse]) responses: The responses from creating the portfolio in each scope
    """
    # The date your portfolio was first created
    portfolio_creation_date = datetime.now(pytz.UTC) - timedelta(days=5000)

    responses = []

    for scope in scopes:

        try:
            api_factory.build(lusid.api.PortfoliosApi).delete_portfolio(
                scope=scope, code=code
            )
        except lusid.ApiException as e:
            pass

        # Create the request to add your portfolio to LUSID
        transaction_portfolio_request = models.CreateTransactionPortfolioRequest(
            display_name="Global Fund",
            code=code,
            base_currency=currency,
            created=portfolio_creation_date,
            sub_holding_keys=None,
        )

        # Call LUSID to create your portfolio
        response = api_factory.build(
            lusid.api.TransactionPortfoliosApi
        ).create_portfolio(
            scope=scope,
            create_transaction_portfolio_request=transaction_portfolio_request,
        )

        responses.append(response)

    return responses
    def test_create_portfolio(self):
        guid = str(uuid.uuid4())

        # details of the new portfolio to be created, created here with the minimum set of mandatory fields
        request = models.CreateTransactionPortfolioRequest(

            # descriptive name for the portfolio
            display_name="portfolio-{0}".format(guid),

            # unique portfolio code, portfolio codes must be unique across scopes
            code="id-{0}".format(guid),
            base_currency="GBP")

        # create the portfolio in LUSID in the specified scope
        result = self.transaction_portfolios_api.create_portfolio(
            scope=TestDataUtilities.tutorials_scope, create_request=request)

        self.assertEqual(result.id.code, request.code)
def setup_portfolio(api_factory, portfolio_scope, portfolio_code,
                    portfolio_created_date, properties: dict):
    # Create portfolio and assign the corp action source
    portfolio_request = models.CreateTransactionPortfolioRequest(
        display_name=portfolio_code,
        code=portfolio_code,
        base_currency="GBP",
        created=portfolio_created_date,
        properties=properties)

    try:
        api_factory.build(lusid.api.TransactionPortfoliosApi).create_portfolio(
            scope=portfolio_scope,
            create_transaction_portfolio_request=portfolio_request)
    except ApiException:
        print(
            f"Portfolio with code {portfolio_code} and scope {portfolio_scope} already exists"
        )
Esempio n. 9
0
    def create_transaction_portfolio(self, scope):
        guid = str(uuid.uuid4())

        # Effective date of the portfolio, this is the date the portfolio was created and became live.
        # All dates/times must be supplied in UTC
        effective_date = datetime(2018, 1, 1, tzinfo=pytz.utc)

        # Details of the new portfolio to be created, created here with the minimum set of mandatory fields
        request = models.CreateTransactionPortfolioRequest(display_name="Portfolio-{}".format(guid),
                                                           code="Id-{}".format(guid),
                                                           base_currency="GBP",
                                                           created=effective_date)

        # Create the portfolio in LUSID
        portfolio = self.transaction_portfolio_api.create_portfolio(scope, transaction_portfolio=request)

        assert (portfolio.id.code == request.code)

        return portfolio.id.code
Esempio n. 10
0
def request_transaction_portfolio_creation(portfolio_code,
                                           portfolio_creation_date,
                                           analyst_scope_code, description,
                                           api_factory):

    # Create the request to add our portfolio
    transaction_portfolio_request = models.CreateTransactionPortfolioRequest(
        display_name=portfolio_code,
        code=portfolio_code,
        base_currency='GBP',
        description='Paper transaction portfolio',
        created=portfolio_creation_date)

    # Call LUSID to create our portfolio
    portfolio_response = api_factory.build(
        lusid.api.TransactionPortfoliosApi).create_portfolio(
            scope=analyst_scope_code,
            create_transaction_portfolio_request=transaction_portfolio_request)

    # Pretty print the response from LUSID
    prettyprint.portfolio_response(portfolio_response)
Esempio n. 11
0
    def create_portfolio(self):
        # Details of new portfolio to be created
        effective_date = datetime(2020, 12, 1, 0, 0, tzinfo=pytz.utc)
        create_portfolio_request = models.CreateTransactionPortfolioRequest(
            code=self.code,
            display_name=self.code,
            base_currency="GBP",
            created=effective_date,
        )

        # create portfolio
        try:
            self.transaction_portfolios_api.create_portfolio(
                scope=self.scope,
                create_transaction_portfolio_request=create_portfolio_request,
            )
        except lusid.ApiException as e:
            if json.loads(e.body)["name"] == "PortfolioWithIdAlreadyExists":
                self.root_logger.info(
                    f"Portfolio {create_portfolio_request.code} already exists"
                )
Esempio n. 12
0
    def test_create_portfolio(self):

        _, scope, portfolio_code = self.id_generator.generate_scope_and_code(
            "portfolio",
            scope=TestDataUtilities.tutorials_scope,
            code_prefix="portfolio-")

        # details of the new portfolio to be created, created here with the minimum set of mandatory fields
        request = models.CreateTransactionPortfolioRequest(

            # descriptive name for the portfolio
            display_name=portfolio_code,

            # unique portfolio code, portfolio codes must be unique across scopes
            code=portfolio_code,
            base_currency="GBP")

        # create the portfolio in LUSID in the specified scope
        result = self.transaction_portfolios_api.create_portfolio(
            scope=scope, create_transaction_portfolio_request=request)

        self.assertEqual(result.id.code, request.code)
    def test_12_pg_add_portfolios_different_scopes(self) -> None:

        """
        Test description:
        -----------------
        Here we test adding portfolios with multiple scopes.

        Expected outcome:
        -----------------
        Request should be successful - returned with portfolios with multiple scopes.

        """

        test_case_scope = create_scope_id()
        data_frame = self.csv_to_data_frame_with_scope(
            "data/port_group_tests/test_12_pg_add_portfolios_different_scopes.csv",
            self.portfolio_scope,
        )

        port_scope_for_test = create_scope_id()
        self.api_factory.build(lusid.api.TransactionPortfoliosApi).create_portfolio(
            scope=port_scope_for_test,
            create_transaction_portfolio_request=models.CreateTransactionPortfolioRequest(
                display_name=data_frame["FundCode"][0],
                code=data_frame["FundCode"][0],
                base_currency="GBP",
            ),
        )

        port_group_request = lusid.models.CreatePortfolioGroupRequest(
            code=data_frame["PortGroupCode"][0],
            display_name=data_frame["PortGroupCode"][0],
            values=[
                lusid.models.ResourceId(
                    code=data_frame["FundCode"][0], scope=port_scope_for_test
                )
            ],
        )

        self.api_factory.build(lusid.api.PortfolioGroupsApi).create_portfolio_group(
            scope=test_case_scope, create_portfolio_group_request=port_group_request,
        )

        responses = self.cocoon_load_from_dataframe(
            scope=test_case_scope, data_frame=data_frame,
        )

        self.log_error_requests_title("portfolio_groups", responses)

        self.assertTrue(
            expr=all(
                [
                    id in responses["portfolio_groups"]["success"][0].portfolios
                    for id in [
                        lusid.models.ResourceId(
                            code=data_frame["FundCode"][1], scope=data_frame["Scope"][1]
                        ),
                        lusid.models.ResourceId(
                            code=data_frame["FundCode"][0], scope=port_scope_for_test
                        ),
                        lusid.models.ResourceId(
                            code=data_frame["FundCode"][0], scope=data_frame["Scope"][0]
                        ),
                        lusid.models.ResourceId(
                            code=data_frame["FundCode"][2], scope=data_frame["Scope"][2]
                        ),
                    ]
                ]
            )
        )
Esempio n. 14
0
    token=lusid.utilities.RefreshingToken(config),
    api_secrets_filename=secrets_file_path)
api_client = api_factory.api_client
instruments_api = api_factory.build(lusid.api.InstrumentsApi)
tx_portfolios_api = api_factory.build(lusid.api.TransactionPortfoliosApi)

# Create a portfolio

# You need to set the timezone or it will throw an error
portfolio_creation_date = datetime.datetime(2021, 3, 20, tzinfo=pytz.utc)
scope = "GettingStartedScope"
guid = uuid.uuid4()

portfolio_request = models.CreateTransactionPortfolioRequest(
    display_name=f"Portfolio-{guid}",
    code=f"Id-{guid}",
    base_currency="GBP",
    created=portfolio_creation_date)

portfolio = tx_portfolios_api.create_portfolio(
    scope, create_transaction_portfolio_request=portfolio_request)
portfolio_code = portfolio.id.code
print("portfolio:", portfolio_code)

# Add instruments
# FIGIs are from https://www.openfigi.com/search#!?page=1
figis_to_create = {
    figi: models.InstrumentDefinition(
        name=name, identifiers={"Figi": models.InstrumentIdValue(value=figi)})
    for figi, name in [("BBG000C6K6G9",
                        "VODAFONE GROUP PLC"), ("BBG000C04D57",
    def test_create_portfolio_with_mv_property(self):
        # Details of property to be created
        effective_date = datetime(year=2018, month=1, day=1, tzinfo=pytz.utc)
        scope = "MultiValueProperties"
        code = "MorningstarQuarterlyRating"
        portfolio_code = "Portfolio-MVP"

        multi_value_property_definition = models.CreatePropertyDefinitionRequest(
            domain="Portfolio",
            scope=scope,
            code=code,
            display_name=code,
            constraint_style="Collection",
            data_type_id=lusid.ResourceId(scope="system", code="string"),
        )

        # create property definition
        try:
            self.property_definitions_api.create_property_definition(
                create_property_definition_request=
                multi_value_property_definition)
        except lusid.ApiException as e:
            if json.loads(e.body)["name"] == "PropertyAlreadyExists":
                logging.info(
                    f"Property {multi_value_property_definition.domain}/{multi_value_property_definition.scope}/{multi_value_property_definition.display_name} already exists"
                )
        finally:
            self.id_generator.add_scope_and_code(
                "property_definition", multi_value_property_definition.scope,
                multi_value_property_definition.code, ["Portfolio"])

        schedule = [
            '{ "2019-12-31" : "5"}',
            '{ "2020-03-31" : "4"}',
            '{ "2020-06-30" : "3"}',
            '{ "2020-09-30" : "3"}',
        ]

        # Details of new portfolio to be created
        create_portfolio_request = models.CreateTransactionPortfolioRequest(
            code=portfolio_code,
            display_name=portfolio_code,
            base_currency="GBP",
            created=effective_date,
        )

        # create portfolio
        try:
            self.transaction_portfolios_api.create_portfolio(
                scope=scope,
                create_transaction_portfolio_request=create_portfolio_request,
            )
        except lusid.ApiException as e:
            if json.loads(e.body)["name"] == "PortfolioWithIdAlreadyExists":
                logging.info(
                    f"Portfolio {create_portfolio_request.code} already exists"
                )
        finally:
            self.id_generator.add_scope_and_code("portfolio", scope,
                                                 portfolio_code)

        self.portfolios_api.upsert_portfolio_properties(
            scope=scope,
            code=portfolio_code,
            request_body={
                f"Portfolio/{scope}/{code}":
                models.ModelProperty(
                    key=f"Portfolio/{scope}/{code}",
                    value=models.PropertyValue(
                        label_value_set=models.LabelValueSet(values=schedule)),
                )
            },
        )

        # get properties for assertions
        portfolio_properties = self.portfolios_api.get_portfolio_properties(
            scope=scope, code=portfolio_code).properties
        label_value_set = portfolio_properties[
            f"Portfolio/MultiValueProperties/{code}"].value.label_value_set.values
        self.assertCountEqual(label_value_set, schedule)
Esempio n. 16
0
config = ApiConfigurationLoader.load(secrets_file_path)
api_factory = lusid.utilities.ApiClientFactory(
    token=lusid.utilities.RefreshingToken(config),
    api_secrets_filename=secrets_file_path
)


# Create portfolio
tx_portfolios_api = api_factory.build(lusid.api.TransactionPortfoliosApi)

scope = "GettingStartedScope"
guid = uuid.uuid4()

portfolio_request = models.CreateTransactionPortfolioRequest(
    display_name=f"Portfolio-{guid}",
    code=f"Id-{guid}",
    base_currency="GBP",
    created=datetime.datetime(2021, 3, 20, tzinfo=pytz.utc)
)

portfolio = tx_portfolios_api.create_portfolio(scope, create_transaction_portfolio_request=portfolio_request)
portfolio_code = portfolio.id.code
print("Porfolio Code:", portfolio_code)

# Upsert instruments
instruments_api = api_factory.build(lusid.api.InstrumentsApi)

# FIGI is from https://www.openfigi.com/id/BBG000C6K6G9
figis_to_create = {
    "BBG000C6K6G9": models.InstrumentDefinition(name="VODAFONE GROUP PLC",
        identifiers={"Figi": models.InstrumentIdValue(value="BBG000C6K6G9")}
    )