def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3,
                           status=3,
                           status_forcelist=frozenset([429, 503]),
                           backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    components_api = ComponentsApi(api_client)
    try:
        spar_document_name = "pmw_root:/spar_documents/Factset Default Document"
        spar_component_name = "Returns Table"
        spar_component_category = "Raw Data / Returns"
        spar_benchmark_1 = "R.1000"
        spar_benchmark_2 = "RUSSELL_P:R.2000"
        spar_benchmark_prefix = "RUSSELL"
        spar_benchmark_return_type = "GTR"
        startdate = "20180101"
        enddate = "20181231"
        frequency = "Monthly"
        currency = "USD"
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
        # cache_control = "max-stale=0"
        get_components_response = components_api.get_spar_components(
            spar_document_name)

        component_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name == spar_component_name
            and get_components_response[0].data[id].category ==
            spar_component_category
        ][0]
        print("SPAR Component Id: " + component_id)
        spar_account_identifier = SPARIdentifier(
            id=spar_benchmark_1,
            returntype=spar_benchmark_return_type,
            prefix=spar_benchmark_prefix)
        spar_accounts = [spar_account_identifier]
        spar_benchmark_identifier = SPARIdentifier(
            id=spar_benchmark_2,
            returntype=spar_benchmark_return_type,
            prefix=spar_benchmark_prefix)
        spar_dates = SPARDateParameters(startdate, enddate, frequency)

        spar_calculation_parameters = {
            "1":
            SPARCalculationParameters(componentid=component_id,
                                      accounts=spar_accounts,
                                      benchmark=spar_benchmark_identifier,
                                      dates=spar_dates,
                                      currencyisocode=currency)
        }

        spar_calculation_parameter_root = SPARCalculationParametersRoot(
            data=spar_calculation_parameters)

        spar_calculations_api = SPARCalculationsApi(api_client)
        post_and_calculate_response = spar_calculations_api.post_and_calculate(
            spar_calculation_parameters_root=spar_calculation_parameter_root)
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = spar_calculations_api.post_and_calculate(spar_calculation_parameters_root=spar_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result(post_and_calculate_response[0]['data'])
        elif post_and_calculate_response[1] == 200:
            for (calculation_unit_id, calculation_unit
                 ) in post_and_calculate_response[0].data.units.items():
                print("Calculation Unit Id:" + calculation_unit_id +
                      " Failed!!!")
                print("Error message : " + str(calculation_unit.errors))
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = spar_calculations_api.get_calculation_status_by_id(
                id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status
                                                 in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = spar_calculations_api.get_calculation_status_by_id(
                    calculation_id)

            for (calculation_unit_id,
                 calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " + calculation_unit_id +
                          " Succeeded!!!")
                    result_response = spar_calculations_api.get_calculation_unit_result_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    output_calculation_result(result_response[0]['data'])
                else:
                    print("Calculation Unit Id:" + calculation_unit_id +
                          " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))
    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
Ejemplo n.º 2
0
    def run_calculation(self):
        components_api = ComponentsApi(self.api_client)
        components = components_api.get_pa_components(
            common_parameters.pa_deafult_document)
        component_id = list(components.keys())[0]

        pa_account_identifier = PAIdentifier(
            common_parameters.pa_benchmark_sp500)
        pa_accounts = [pa_account_identifier]
        pa_benchmark_identifier = PAIdentifier(
            common_parameters.pa_benchmark_r1000)
        pa_benchmarks = [pa_benchmark_identifier]
        pa_dates = PADateParameters(common_parameters.deafult_start_date,
                                    common_parameters.deafult_end_date,
                                    common_parameters.deafult_dates_frequency)

        pa_calculation_parameters = {
            "1":
            PACalculationParameters(component_id, pa_accounts, pa_benchmarks,
                                    pa_dates)
        }

        components = components_api.get_spar_components(
            common_parameters.spar_deafult_document)
        component_id = list(components.keys())[0]

        spar_account_identifier = SPARIdentifier(
            common_parameters.spar_benchmark_r1000,
            common_parameters.spar_benchmark_russell_return_type,
            common_parameters.spar_benchmark_russell_prefix)
        spar_accounts = [spar_account_identifier]
        spar_benchmark_identifier = SPARIdentifier(
            common_parameters.spar_benchmark_r2000,
            common_parameters.spar_benchmark_russell_return_type,
            common_parameters.spar_benchmark_russell_prefix)
        spar_dates = SPARDateParameters(
            common_parameters.deafult_start_date,
            common_parameters.deafult_end_date,
            common_parameters.deafult_dates_frequency)

        spar_calculation_parameters = {
            "2":
            SPARCalculationParameters(component_id, spar_accounts,
                                      spar_benchmark_identifier, spar_dates)
        }

        components = components_api.get_vault_components(
            common_parameters.vault_deafult_document)
        component_id = list(components.keys())[0]

        vault_account_identifier = VaultIdentifier(
            common_parameters.vault_deafult_account)
        vault_dates = VaultDateParameters(
            common_parameters.vault_start_date,
            common_parameters.vault_end_date,
            common_parameters.deafult_dates_frequency)

        configurations_api = ConfigurationsApi(self.api_client)
        configurations = configurations_api.get_vault_configurations(
            common_parameters.vault_deafult_account)
        configuration_id = list(configurations.keys())[0]

        vault_calculation_parameters = {
            "3":
            VaultCalculationParameters(component_id, vault_account_identifier,
                                       vault_dates, configuration_id)
        }

        calculation = Calculation(pa_calculation_parameters,
                                  spar_calculation_parameters,
                                  vault_calculation_parameters)
        return self.calculations_api.run_calculation_with_http_info(
            calculation=calculation)
Ejemplo n.º 3
0
class TestComponentsApi(unittest.TestCase):
    def setUp(self):
        self.components_api = ComponentsApi(CommonFunctions.build_api_client())

    ######################################################################################
    # PA Components Test Cases
    ######################################################################################

    def test_get_all_pa_components(self):
        response = self.components_api.get_pa_components(
            document=common_parameters.pa_default_document,
            _return_http_data_only=False)
        component_id = list(response[0]['data'].keys())[0]
        self.assertEqual(response[1], 200, "Response should be 200 - Success")
        self.assertEqual(type(response[0]), ComponentSummaryRoot,
                         "Response should be of dictionary type")
        self.assertEqual(type(response[0]['data'][component_id]),
                         ComponentSummary,
                         "Response should be of ComponentSummary type")

    # This test encounters ApiTypeException due to response having fields set to null instead of being hidden
    @unittest.skip(
        "Skip until fix API behavior where null property is returned instead of hidden"
    )
    def test_get_pa_component_by_id(self):
        components = self.components_api.get_pa_components(
            document=common_parameters.pa_default_document)
        component_id = list(components['data'].keys())[0]
        response = self.components_api.get_pa_component_by_id(
            id=component_id, _return_http_data_only=False)
        self.assertEqual(response[1], 200, "Response should be 200 - Success")
        self.assertEqual(type(response[0]), PAComponentRoot,
                         "Response should be of PAComponentRoot type.")
        self.assertEqual(type(response[0]['data'][component_id]),
                         ComponentSummary,
                         "Response should be of ComponentSummary type")

    ######################################################################################
    # Vault Components Test Cases
    ######################################################################################

    def test_get_all_vault_components(self):
        response = self.components_api.get_vault_components(
            document=common_parameters.vault_default_document,
            _return_http_data_only=False)
        component_id = list(response[0]['data'].keys())[0]
        self.assertEqual(response[1], 200, "Response should be 200 - Success")
        self.assertEqual(type(response[0]), ComponentSummaryRoot,
                         "Response should be of dictionary type")
        self.assertEqual(type(response[0]['data'][component_id]),
                         ComponentSummary,
                         "Response should be of ComponentSummary type")

    # This test encounters ApiTypeException due to response having fields set to null instead of being hidden
    @unittest.skip(
        "Skip until fix API behavior where null property is returned instead of hidden"
    )
    def test_get_vault_component_by_id(self):
        components = self.components_api.get_vault_components(
            document=common_parameters.vault_default_document)
        component_id = list(components['data'].keys())[0]
        response = self.components_api.get_vault_component_by_id(
            component_id, _return_http_data_only=False)
        component_id = list(response[0]['data'].keys())[0]
        self.assertEqual(response[1], 200, "Response should be 200 - Success")
        self.assertEqual(type(response[0]['data']), VaultComponent,
                         "Response should be of VaultComponent type.")

    ######################################################################################
    # Spar Components Test Cases
    ######################################################################################

    def test_get_all_spar_components(self):
        response = self.components_api.get_spar_components(
            document=common_parameters.spar_default_document,
            _return_http_data_only=False)
        component_id = list(response[0]['data'].keys())[0]
        self.assertEqual(response[1], 200, "Response should be 200 - Success")
        self.assertEqual(type(response[0]), ComponentSummaryRoot,
                         "Response should be of dictionary type")
        self.assertEqual(type(response[0]['data'][component_id]),
                         ComponentSummary,
                         "Response should be of ComponentSummary type")
enddate = "20181231"
frequency = "Monthly"

config = Configuration()
config.host = host
config.username = username
config.password = password
# add proxy and/or disable ssl verification according to your development environment
# config.proxy = "<proxyUrl>"
config.verify_ssl = False

api_client = ApiClient(config)

components_api = ComponentsApi(api_client)

components = components_api.get_spar_components(spar_document_name)
component_id = list((dict(filter(lambda component: (component[1].name == spar_component_name and component[1].category == spar_component_category), components.items()))).keys())[0]

spar_account_identifier = SPARIdentifier(spar_benchmark_r_1000, spar_benchmark_russell_return_type, spar_benchmark_russell_prefix)
spar_accounts = [spar_account_identifier]
spar_benchmark_identifier = SPARIdentifier(spar_benchmark_russell_pr_2000, spar_benchmark_russell_return_type, spar_benchmark_russell_prefix)
spar_dates = SPARDateParameters(startdate, enddate, frequency)

spar_calculation_parameters = {"2": SPARCalculationParameters(component_id, spar_accounts, spar_benchmark_identifier, spar_dates)}

calculation = Calculation(spar=spar_calculation_parameters)
print(calculation)

calculations_api = CalculationsApi(api_client)
run_calculation_response = calculations_api.run_calculation_with_http_info(calculation=calculation)
Ejemplo n.º 5
0
class TestSparCalculationsApi(unittest.TestCase):
    def setUp(self):
        api_client = CommonFunctions.build_api_client()
        self.spar_calculations_api = SPARCalculationsApi(api_client)
        self.components_api = ComponentsApi(api_client)

    def test_single_unit_scenario(self):
        create_step_name = "create_calculation"
        read_status_step_name = "read_status"
        read_result_step_name = "read_result"

        def create_calculation(test_context):
            print("Creating single unit calculation")
            components = self.components_api.get_spar_components(
                document="SPAR_DOCUMENTS:/Factset Default Document",
                _return_http_data_only=True)
            component_summary = ComponentSummary(name="Returns Table",
                                                 category="Raw Data / Returns")
            component_id = [
                id for id in list(components.data.keys())
                if components.data[id] == component_summary
            ][0]
            spar_accounts = [SPARIdentifier(id="R.1000")]
            spar_benchmarks = SPARIdentifier(id="RUSSELL_P:R.2000")
            spar_dates = SPARDateParameters(startdate="20180101",
                                            enddate="20181231",
                                            frequency="Monthly")

            spar_calculation_parameters = {
                "1":
                SPARCalculationParameters(componentid=component_id,
                                          accounts=spar_accounts,
                                          benchmark=spar_benchmarks,
                                          dates=spar_dates)
            }

            spar_calculation_parameter_root = SPARCalculationParametersRoot(
                data=spar_calculation_parameters)

            post_and_calculate_response = self.spar_calculations_api.post_and_calculate(
                spar_calculation_parameters_root=
                spar_calculation_parameter_root,
                cache_control='max-stale=0')

            self.assertTrue(
                post_and_calculate_response[1] == 201
                or post_and_calculate_response[1] == 202,
                "Response for create_calculation should have been 201 or 202")

            if post_and_calculate_response[1] == 201:
                return {
                    "continue_workflow": False,
                    "next_request": None,
                    "test_context": None
                }
            elif post_and_calculate_response[1] == 202:
                test_context["calculation_id"] = post_and_calculate_response[
                    2]["X-Factset-Api-Calculation-Id"]
                return {
                    "continue_workflow": True,
                    "next_request": read_status_step_name,
                    "test_context": test_context
                }

        def read_calculation_status(test_context):
            print("Reading single unit calculation status")
            calculation_id = test_context["calculation_id"]
            print("Calculation Id: " + calculation_id)

            status_response = self.spar_calculations_api.get_calculation_status_by_id(
                id=calculation_id)

            self.assertTrue(
                status_response[1] == 202 and
                (status_response[0].data.status in ("Queued", "Executing")))

            while status_response[1] == 202 and (status_response[0].data.status
                                                 in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = self.spar_calculations_api.get_calculation_status_by_id(
                    id=calculation_id)

                test_context["calculation_units"] = status_response[
                    0].data.units.items()

            return {
                "continue_workflow": True,
                "next_request": read_result_step_name,
                "test_context": test_context
            }

        def read_calculation_unit_result(test_context):
            calculation_id = test_context["calculation_id"]
            for (calculation_unit_id,
                 calculation_unit) in test_context["calculation_units"]:
                result_response = self.spar_calculations_api.get_calculation_unit_result_by_id(
                    id=calculation_id, unit_id=calculation_unit_id)
                self.assertEqual(
                    result_response[1], 200,
                    "Get calculation result should have succeeded")

        workflow_specification = {
            create_step_name: create_calculation,
            read_status_step_name: read_calculation_status,
            read_result_step_name: read_calculation_unit_result
        }
        starting_request = workflow_specification['create_calculation']
        test_context = {}
        run_api_workflow_with_assertions(workflow_specification,
                                         starting_request, test_context)