def build_api_client():
        if (common_parameters.user_name and common_parameters.password):
            config = Configuration()
            config.host = common_parameters.base_url
            config.username = common_parameters.user_name
            config.password = common_parameters.password
            config.verify_ssl = False

            return ApiClient(config)

        raise ValueError(
            "Please set ANALYTICS_API_USERNAME_SERIAL and ANALYTICS_API_PASSWORD environment variables."
        )
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __get_pa_groups(self, **kwargs):
            """Get PA groups  # noqa: E501

            This endpoint lists all the PA groups that can be applied to a PA calculation.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_pa_groups(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                GroupRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.get_pa_groups = _Endpoint(settings={
            'response_type':
            dict({
                200: (GroupRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/pa/v3/groups',
            'operation_id':
            'get_pa_groups',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                       params_map={
                                           'all': [],
                                           'required': [],
                                           'nullable': [],
                                           'enum': [],
                                           'validation': []
                                       },
                                       root_map={
                                           'validations': {},
                                           'allowed_values': {},
                                           'openapi_types': {},
                                           'attribute_map': {},
                                           'location_map': {},
                                           'collection_format_map': {}
                                       },
                                       headers_map={
                                           'accept': ['application/json'],
                                           'content_type': [],
                                       },
                                       api_client=api_client,
                                       callable=__get_pa_groups)
예제 #3
0
 def __init__(self, api_client=None):
     if api_client is None:
         api_client = ApiClient()
     self.api_client = api_client
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)

    calculations = [
        "Security Type", "Security Name", "Run Status",
        "Elapse Time (seconds)", "Calc From Method", "Option Pricing Model",
        "Yield Curve Date", "Settlement Date", "Discount Curve", "Price",
        "Yield to No Call", "OAS", "Effective Duration", "Effective Convexity",
        "CF Coupon"
    ]

    security1 = FISecurity(calc_from_method="Price",
                           calc_from_value=100.285,
                           face=10000.0,
                           symbol="912828ZG8",
                           settlement="20201202",
                           discount_curve="UST")
    security2 = FISecurity(calc_from_method="Price",
                           calc_from_value=101.138,
                           face=200000.0,
                           symbol="US037833AR12",
                           settlement="20201203",
                           discount_curve="UST")

    # 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"

    securities = [security1, security2]

    jobSettings = FIJobSettings(as_of_date="20201201",
                                partial_duration_months=[1, 3, 6])

    fi_calculation_parameters = FICalculationParameters(
        securities, calculations, jobSettings)

    fi_calculation_parameters_root = FICalculationParametersRoot(
        data=fi_calculation_parameters)

    fi_calculations_api = FICalculationsApi(api_client)
    run_calculation_response = fi_calculations_api.post_and_calculate(
        fi_calculation_parameters_root=fi_calculation_parameters_root)
    # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
    # run_calculation_response = fi_calculations_api.post_and_calculate(
    # fi_calculation_parameters_root=fi_calculation_parameters_root, cache_control=cache_control)
    if run_calculation_response[1] != 202 and run_calculation_response[
            1] != 201:
        print_error(run_calculation_response)
        sys.exit()

    if run_calculation_response[1] == 201:
        output_calculation_result(run_calculation_response[0].data)
        sys.exit()

    calculation_id = run_calculation_response[2][
        "X-Factset-Api-Calculation-Id"]
    print("Calculation Id: " + calculation_id)

    status_response = fi_calculations_api.get_calculation_status_by_id(
        id=calculation_id)
    while status_response[1] == 202:
        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 = fi_calculations_api.get_calculation_status_by_id(
            id=calculation_id)

    if status_response[1] != 201:
        print_error(status_response)
        sys.exit()

    output_calculation_result(status_response[0].data)
예제 #5
0
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __cancel_optimization_by_id(self, id, **kwargs):
            """Cancel AFI optimization by id  # noqa: E501

            This is the endpoint to cancel a previously submitted optimization.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.cancel_optimization_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run AFI optimization endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                None
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.cancel_optimization_by_id = _Endpoint(
            settings={
                'response_type': None,
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/afi/v3/optimizations/{id}',
                'operation_id': 'cancel_optimization_by_id',
                'http_method': 'DELETE',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['text/plain', 'application/json', 'text/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__cancel_optimization_by_id)

        def __get_optimization_parameters(self, id, **kwargs):
            """Get AFI optimization parameters by id  # noqa: E501

            This is the endpoint that returns the optimization parameters passed for an optimization.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_optimization_parameters(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run AFI optimization endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                AFIOptimizationParametersRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_optimization_parameters = _Endpoint(
            settings={
                'response_type': dict({
                    200: (AFIOptimizationParametersRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/afi/v3/optimizations/{id}',
                'operation_id': 'get_optimization_parameters',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_optimization_parameters)

        def __get_optimization_result(self, id, **kwargs):
            """Get AFI optimization result by id  # noqa: E501

            This is the endpoint to get the result of a previously requested optimization.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_optimization_result(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Get AFI optimization status by id endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                ObjectRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_optimization_result = _Endpoint(
            settings={
                'response_type': dict({
                    200: (ObjectRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/afi/v3/optimizations/{id}/result',
                'operation_id': 'get_optimization_result',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_optimization_result)

        def __get_optimization_status_by_id(self, id, **kwargs):
            """Get AFI optimization status by id  # noqa: E501

            This is the endpoint to check on the progress of a previously requested optimization.  If the optimization has finished computing, the body of the response will contain result in JSON.  Otherwise, the optimization is still running and the X-FactSet-Api-PickUp-Progress header will contain a progress percentage.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_optimization_status_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run AFI optimization endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                (For 201 status - ObjectRoot)(For 202 status - None)
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_optimization_status_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    201: (ObjectRoot, ),
                    202: None,
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/afi/v3/optimizations/{id}/status',
                'operation_id': 'get_optimization_status_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_optimization_status_by_id)

        def __post_and_optimize(self, **kwargs):
            """Create and Run AFI optimization  # noqa: E501

            This endpoint creates and runs AFI optimization specified in the POST body parameters.                Remarks:                * Any settings in POST body will act as a one-time override over the settings saved in the strategy document.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.post_and_optimize(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                x_fact_set_api_long_running_deadline (int): Long running deadline in seconds.. [optional]
                cache_control (str): Standard HTTP header.  Accepts max-stale.. [optional]
                afi_optimization_parameters_root (AFIOptimizationParametersRoot): Optimization Parameters. [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                (For 202 status - CalculationInfoRoot)(For 201 status - ObjectRoot)
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.post_and_optimize = _Endpoint(
            settings={
                'response_type':
                dict({
                    202: (CalculationInfoRoot, ),
                    201: (ObjectRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/afi/v3/optimizations',
                'operation_id':
                'post_and_optimize',
                'http_method':
                'POST',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'x_fact_set_api_long_running_deadline',
                    'cache_control',
                    'afi_optimization_parameters_root',
                ],
                'required': [],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'x_fact_set_api_long_running_deadline': (int, ),
                    'cache_control': (str, ),
                    'afi_optimization_parameters_root':
                    (AFIOptimizationParametersRoot, ),
                },
                'attribute_map': {
                    'x_fact_set_api_long_running_deadline':
                    'X-FactSet-Api-Long-Running-Deadline',
                    'cache_control': 'Cache-Control',
                },
                'location_map': {
                    'x_fact_set_api_long_running_deadline': 'header',
                    'cache_control': 'header',
                    'afi_optimization_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__post_and_optimize)

        def __put_and_optimize(self, id, **kwargs):
            """Create or Update AFI optimization and run it.  # noqa: E501

            This endpoint updates and run the AFI optimization specified in the PUT body parameters. It also allows the creation of new AFI optimization with custom id.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.put_and_optimize(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run AFI optimization endpoint

            Keyword Args:
                x_fact_set_api_long_running_deadline (int): Long running deadline in seconds.. [optional]
                cache_control (str): Standard HTTP header.  Accepts max-stale.. [optional]
                afi_optimization_parameters_root (AFIOptimizationParametersRoot): Optimization Parameters. [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                (For 202 status - CalculationInfoRoot)(For 201 status - ObjectRoot)
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.put_and_optimize = _Endpoint(
            settings={
                'response_type':
                dict({
                    202: (CalculationInfoRoot, ),
                    201: (ObjectRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/afi/v3/optimizations/{id}',
                'operation_id':
                'put_and_optimize',
                'http_method':
                'PUT',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'id',
                    'x_fact_set_api_long_running_deadline',
                    'cache_control',
                    'afi_optimization_parameters_root',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                    'x_fact_set_api_long_running_deadline': (int, ),
                    'cache_control': (str, ),
                    'afi_optimization_parameters_root':
                    (AFIOptimizationParametersRoot, ),
                },
                'attribute_map': {
                    'id': 'id',
                    'x_fact_set_api_long_running_deadline':
                    'X-FactSet-Api-Long-Running-Deadline',
                    'cache_control': 'Cache-Control',
                },
                'location_map': {
                    'id': 'path',
                    'x_fact_set_api_long_running_deadline': 'header',
                    'cache_control': 'header',
                    'afi_optimization_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__put_and_optimize)
예제 #6
0
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:
        pa_document_name = "PA_DOCUMENTS:DEFAULT"
        pa_component_name = "Weights"
        pa_component_category = "Weights / Exposures"
        portfolio = "BENCH:SP50"
        benchmark = "BENCH:R.1000"
        startdate = "20180101"
        enddate = "20181231"
        frequency = "Monthly"
        # 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_pa_components(
            document=pa_document_name)
        component_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name == pa_component_name
            and get_components_response[0].data[id].category ==
            pa_component_category
        ][0]
        print("PA Component Id: " + component_id)
        pa_accounts = [PAIdentifier(id=portfolio)]
        pa_benchmarks = [PAIdentifier(id=benchmark)]
        pa_dates = PADateParameters(startdate=startdate,
                                    enddate=enddate,
                                    frequency=frequency)

        pa_calculation_parameters = {
            "1":
            PACalculationParameters(componentid=component_id,
                                    accounts=pa_accounts,
                                    benchmarks=pa_benchmarks,
                                    dates=pa_dates),
            "2":
            PACalculationParameters(componentid=component_id,
                                    accounts=pa_accounts,
                                    benchmarks=pa_benchmarks,
                                    dates=pa_dates)
        }

        pa_calculation_parameter_root = PACalculationParametersRoot(
            data=pa_calculation_parameters)

        pa_calculations_api = PACalculationsApi(api_client)

        post_and_calculate_response = pa_calculations_api.post_and_calculate(
            pa_calculation_parameters_root=pa_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 = pa_calculations_api.post_and_calculate(pa_calculation_parameters_root=pa_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[
                1] == 202 or post_and_calculate_response[1] == 200:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = pa_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 = pa_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 = pa_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))
        else:
            print("Calculation creation failed")
            print("Error status : " + str(post_and_calculate_response[1]))
            print("Error message : " + str(post_and_calculate_response[0]))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
예제 #7
0
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __create_templated_pa_components(
                self, templated_pa_component_parameters_root, **kwargs):
            """Create templated PA component  # noqa: E501

            This endpoint creates new component based off of linked PA template or unlinked PA template.    Remarks:    *   Any settings in the POST body will act as a one-time override over the settings saved in the PA template.    *   Multi-horizon frequencies are not supported through this endpoint.    *   Componentdetail supports securities, groups, and totals as well but if we don't pass anything that defaults to securities.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.create_templated_pa_components(templated_pa_component_parameters_root, async_req=True)
            >>> result = thread.get()

            Args:
                templated_pa_component_parameters_root (TemplatedPAComponentParametersRoot): Request Parameters

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                TemplatedPAComponentPostSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['templated_pa_component_parameters_root'] = \
                templated_pa_component_parameters_root
            return self.call_with_http_info(**kwargs)

        self.create_templated_pa_components = _Endpoint(
            settings={
                'response_type':
                dict({
                    201: (TemplatedPAComponentPostSummaryRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/templated-components',
                'operation_id':
                'create_templated_pa_components',
                'http_method':
                'POST',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'templated_pa_component_parameters_root',
                ],
                'required': [
                    'templated_pa_component_parameters_root',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'templated_pa_component_parameters_root':
                    (TemplatedPAComponentParametersRoot, ),
                },
                'attribute_map': {},
                'location_map': {
                    'templated_pa_component_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['text/plain', 'application/json', 'text/json'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__create_templated_pa_components)

        def __delete_templated_pa_components(self, id, **kwargs):
            """Delete templated PA component  # noqa: E501

            This endpoint deletes an existing templated PA component  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.delete_templated_pa_components(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for a templated PA component

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                None
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.delete_templated_pa_components = _Endpoint(
            settings={
                'response_type': None,
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/templated-components/{id}',
                'operation_id': 'delete_templated_pa_components',
                'http_method': 'DELETE',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['text/plain', 'application/json', 'text/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__delete_templated_pa_components)

        def __get_templated_pa_component_by_id(self, id, **kwargs):
            """Get templated PA component by id  # noqa: E501

            This endpoint fetches the templated PA component settings.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_templated_pa_component_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for a templated PA component

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                TemplatedPAComponentRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_templated_pa_component_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    200: (TemplatedPAComponentRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/templated-components/{id}',
                'operation_id': 'get_templated_pa_component_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_templated_pa_component_by_id)

        def __get_templated_pa_components_in_path(self, directory, **kwargs):
            """Get templated PA components in path  # noqa: E501

            This endpoint returns the list of templated PA components in path.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_templated_pa_components_in_path(directory, async_req=True)
            >>> result = thread.get()

            Args:
                directory (str): Get templated PA components in path

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                TemplatedPAComponentSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['directory'] = \
                directory
            return self.call_with_http_info(**kwargs)

        self.get_templated_pa_components_in_path = _Endpoint(
            settings={
                'response_type': dict({
                    200: (TemplatedPAComponentSummaryRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/templated-components',
                'operation_id': 'get_templated_pa_components_in_path',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'directory',
                ],
                'required': [
                    'directory',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'directory': (str, ),
                },
                'attribute_map': {
                    'directory': 'directory',
                },
                'location_map': {
                    'directory': 'query',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_templated_pa_components_in_path)

        def __update_templated_pa_components(
                self, id, templated_pa_component_update_parameters_root,
                **kwargs):
            """Update templated PA component  # noqa: E501

            This endpoint allows the user to change the request body from an existing templated PA component.    Remarks:    *   Any settings in the POST body will act as a one-time override over the settings saved in the PA template.    *   Multi-horizon frequencies are not supported through this endpoint.    *   Componentdetail supports securities, groups, and totals as well but if we don't pass anything that defaults to securities.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.update_templated_pa_components(id, templated_pa_component_update_parameters_root, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for a templated PA component
                templated_pa_component_update_parameters_root (TemplatedPAComponentUpdateParametersRoot): Request Parameters

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                TemplatedPAComponentPostSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            kwargs['templated_pa_component_update_parameters_root'] = \
                templated_pa_component_update_parameters_root
            return self.call_with_http_info(**kwargs)

        self.update_templated_pa_components = _Endpoint(
            settings={
                'response_type':
                dict({
                    200: (TemplatedPAComponentPostSummaryRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/templated-components/{id}',
                'operation_id':
                'update_templated_pa_components',
                'http_method':
                'PUT',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'id',
                    'templated_pa_component_update_parameters_root',
                ],
                'required': [
                    'id',
                    'templated_pa_component_update_parameters_root',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                    'templated_pa_component_update_parameters_root':
                    (TemplatedPAComponentUpdateParametersRoot, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                    'templated_pa_component_update_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__update_templated_pa_components)
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()
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)

    try:
        pub_document_name = "Super_client:/publisher/Equity Snapshot.PUB_BRIDGE_PDF"
        pub_account_id = "BENCH:SP50"
        startdate = "-1M"
        enddate = "0M"
        # 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"
        pub_account_identifier = PubIdentifier(pub_account_id)
        pub_dates = PubDateParameters(enddate, startdate=startdate)

        pub_calculation_parameters = {
            "1": PubCalculationParameters(pub_document_name, pub_account_identifier, pub_dates)
        }

        pub_calculation_parameters_root = PubCalculationParametersRoot(
            data=pub_calculation_parameters)

        pub_calculations_api = PubCalculationsApi(api_client)
        post_and_calculate_response = pub_calculations_api.post_and_calculate(
           pub_calculation_parameters_root=pub_calculation_parameters_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 = pub_calculations_api.post_and_calculate(pub_calculation_parameters_root=pub_calculation_parameters_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result(
                "single_unit", (post_and_calculate_response[0].read()))
        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 = pub_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 = pub_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 = pub_calculations_api.get_calculation_unit_result_by_id(id=calculation_id,
                                                                                             unit_id=calculation_unit_id)

                    output_calculation_result(
                        "single_unit", (result_response[0].read()))
                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()
예제 #10
0
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __create_unlinked_pa_templates(
                self, unlinked_pa_template_parameters_root, **kwargs):
            """Create unlinked PA template  # noqa: E501

            This endpoint creates a template which is not linked to any specific PA3 tile.     Remarks:    *   Mandatory fields are required to be passed in POST requests and Optional fields are not necessary.       If no mandatory fields are passed, then we can use the template as a component and skip the component creation.        *   Mandatory, optional and locked fields can be  \"accounts\", \"benchmarks\", \"groups\", \"columns\", \"dates\", \"currencyisocode\" and \"componentdetail\".    *   We cannot override the Locked fields when creating the Component.    *   Mandatory and locked strings are mutually exclusive.    *   Any settings in the POST body will act as a one-time override over the settings saved in the PA template.    *   Multi-horizon frequencies are not supported through this endpoint.    *   Componentdetail supports securities, groups, and totals as well but if we don't pass anything that defaults to securities.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.create_unlinked_pa_templates(unlinked_pa_template_parameters_root, async_req=True)
            >>> result = thread.get()

            Args:
                unlinked_pa_template_parameters_root (UnlinkedPATemplateParametersRoot): Request Parameters

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                UnlinkedPATemplatePostSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['unlinked_pa_template_parameters_root'] = \
                unlinked_pa_template_parameters_root
            return self.call_with_http_info(**kwargs)

        self.create_unlinked_pa_templates = _Endpoint(
            settings={
                'response_type':
                dict({
                    201: (UnlinkedPATemplatePostSummaryRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/unlinked-templates',
                'operation_id':
                'create_unlinked_pa_templates',
                'http_method':
                'POST',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'unlinked_pa_template_parameters_root',
                ],
                'required': [
                    'unlinked_pa_template_parameters_root',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'unlinked_pa_template_parameters_root':
                    (UnlinkedPATemplateParametersRoot, ),
                },
                'attribute_map': {},
                'location_map': {
                    'unlinked_pa_template_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__create_unlinked_pa_templates)

        def __delete_unlinked_pa_templates(self, id, **kwargs):
            """Delete unlinked PA template  # noqa: E501

            This endpoint deletes an existing unliked PA template.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.delete_unlinked_pa_templates(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for an unlinked PA template

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                None
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.delete_unlinked_pa_templates = _Endpoint(
            settings={
                'response_type': None,
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/unlinked-templates/{id}',
                'operation_id': 'delete_unlinked_pa_templates',
                'http_method': 'DELETE',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__delete_unlinked_pa_templates)

        def __get_default_unlinked_pa_template_types(self, **kwargs):
            """Get default unlinked PA template types.  # noqa: E501

            This endpoint fetches default unlinked PA template types.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_default_unlinked_pa_template_types(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                UnlinkedPATemplateCategoryAndTypeRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.get_default_unlinked_pa_template_types = _Endpoint(
            settings={
                'response_type':
                dict({
                    200: (UnlinkedPATemplateCategoryAndTypeRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/unlinked-templates/template-types',
                'operation_id':
                'get_default_unlinked_pa_template_types',
                'http_method':
                'GET',
                'servers':
                None,
            },
            params_map={
                'all': [],
                'required': [],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {},
                'attribute_map': {},
                'location_map': {},
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_default_unlinked_pa_template_types)

        def __get_details_type(self, id, **kwargs):
            """Get unlinked PA template type details by id.  # noqa: E501

            This endpoint fetches the unlinked PA template type details.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_details_type(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for an unlinked PA template type

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                UnlinkedPATemplateCategoryAndTypeDetailsRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_details_type = _Endpoint(settings={
            'response_type':
            dict({
                200: (UnlinkedPATemplateCategoryAndTypeDetailsRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/pa/v3/unlinked-templates/template-types/{id}',
            'operation_id':
            'get_details_type',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                          params_map={
                                              'all': [
                                                  'id',
                                              ],
                                              'required': [
                                                  'id',
                                              ],
                                              'nullable': [],
                                              'enum': [],
                                              'validation': []
                                          },
                                          root_map={
                                              'validations': {},
                                              'allowed_values': {},
                                              'openapi_types': {
                                                  'id': (str, ),
                                              },
                                              'attribute_map': {
                                                  'id': 'id',
                                              },
                                              'location_map': {
                                                  'id': 'path',
                                              },
                                              'collection_format_map': {}
                                          },
                                          headers_map={
                                              'accept': ['application/json'],
                                              'content_type': [],
                                          },
                                          api_client=api_client,
                                          callable=__get_details_type)

        def __get_unlinked_pa_templates(self, **kwargs):
            """Get unlinked PA templates  # noqa: E501

            This endpoint returns the list of unlinked PA templates.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_unlinked_pa_templates(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                directory (str): Get unlinked PA templates in path.. [optional]
                category (str): Get unlinked PA templates by category.. [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                UnlinkedPATemplateSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.get_unlinked_pa_templates = _Endpoint(
            settings={
                'response_type': dict({
                    200: (UnlinkedPATemplateSummaryRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path': '/analytics/engines/pa/v3/unlinked-templates',
                'operation_id': 'get_unlinked_pa_templates',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'directory',
                    'category',
                ],
                'required': [],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'directory': (str, ),
                    'category': (str, ),
                },
                'attribute_map': {
                    'directory': 'directory',
                    'category': 'category',
                },
                'location_map': {
                    'directory': 'query',
                    'category': 'query',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_unlinked_pa_templates)

        def __get_unlinked_pa_templates_by_id(self, id, **kwargs):
            """Get unlinked PA template details by id  # noqa: E501

            This endpoint fetches the template settings.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_unlinked_pa_templates_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for an unlinked PA template

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                UnlinkedPATemplateRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_unlinked_pa_templates_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    200: (UnlinkedPATemplateRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/unlinked-templates/{id}',
                'operation_id': 'get_unlinked_pa_templates_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_unlinked_pa_templates_by_id)

        def __update_unlinked_pa_templates(
                self, id, unlinked_pa_template_update_parameters_root,
                **kwargs):
            """Update unlinked PA template  # noqa: E501

            This endpoint updates an existing unlinked PA template.    Remarks:                *   Mandatory fields are required to be passed in POST requests and Optional fields are not necessary.       If no mandatory fields are passed, then we can use the template as a component and skip the component creation.        *   Mandatory, optional and locked fields can be  \"accounts\", \"benchmarks\", \"groups\", \"columns\", \"dates\", \"currencyisocode\" and \"componentdetail\".    *   We cannot override the Locked fields when creating the Component.    *   Mandatory and locked strings are mutually exclusive.    *   Any settings in the POST body will act as a one-time override over the settings saved in the PA template.    *   Multi-horizon frequencies are not supported through this endpoint.    *   Componentdetail supports securities, groups, and totals as well but if we don't pass anything that defaults to securities.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.update_unlinked_pa_templates(id, unlinked_pa_template_update_parameters_root, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for an unlinked PA template
                unlinked_pa_template_update_parameters_root (UnlinkedPATemplateUpdateParametersRoot): Request Parameters

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                UnlinkedPATemplatePostSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            kwargs['unlinked_pa_template_update_parameters_root'] = \
                unlinked_pa_template_update_parameters_root
            return self.call_with_http_info(**kwargs)

        self.update_unlinked_pa_templates = _Endpoint(
            settings={
                'response_type':
                dict({
                    200: (UnlinkedPATemplatePostSummaryRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/pa/v3/unlinked-templates/{id}',
                'operation_id':
                'update_unlinked_pa_templates',
                'http_method':
                'PUT',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'id',
                    'unlinked_pa_template_update_parameters_root',
                ],
                'required': [
                    'id',
                    'unlinked_pa_template_update_parameters_root',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                    'unlinked_pa_template_update_parameters_root':
                    (UnlinkedPATemplateUpdateParametersRoot, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                    'unlinked_pa_template_update_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__update_unlinked_pa_templates)
예제 #11
0
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __get_pa3_documents(self, path="", **kwargs):
            """Get PA3 documents and sub-directories in a directory  # noqa: E501

            This endpoint looks up all PA3 documents and sub-directories in a given directory.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_pa3_documents(path="", async_req=True)
            >>> result = thread.get()

            Args:
                path (str): The directory to get the documents and sub-directories in. defaults to "", must be one of [""]

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                DocumentDirectoriesRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['path'] = \
                path
            return self.call_with_http_info(**kwargs)

        self.get_pa3_documents = _Endpoint(settings={
            'response_type':
            dict({
                200: (DocumentDirectoriesRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/pa/v3/documents/{path}',
            'operation_id':
            'get_pa3_documents',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                           params_map={
                                               'all': [
                                                   'path',
                                               ],
                                               'required': [
                                                   'path',
                                               ],
                                               'nullable': [],
                                               'enum': [],
                                               'validation': []
                                           },
                                           root_map={
                                               'validations': {},
                                               'allowed_values': {},
                                               'openapi_types': {
                                                   'path': (str, ),
                                               },
                                               'attribute_map': {
                                                   'path': 'path',
                                               },
                                               'location_map': {
                                                   'path': 'path',
                                               },
                                               'collection_format_map': {}
                                           },
                                           headers_map={
                                               'accept': ['application/json'],
                                               'content_type': [],
                                           },
                                           api_client=api_client,
                                           callable=__get_pa3_documents)

        def __get_pub_documents(self, path="", **kwargs):
            """Gets Publisher documents and sub-directories in a directory  # noqa: E501

            This endpoint looks up all Publisher documents and sub-directories in a given directory.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_pub_documents(path="", async_req=True)
            >>> result = thread.get()

            Args:
                path (str): The directory to get the documents in. defaults to "", must be one of [""]

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                DocumentDirectoriesRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['path'] = \
                path
            return self.call_with_http_info(**kwargs)

        self.get_pub_documents = _Endpoint(settings={
            'response_type':
            dict({
                200: (DocumentDirectoriesRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/pub/v3/documents/{path}',
            'operation_id':
            'get_pub_documents',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                           params_map={
                                               'all': [
                                                   'path',
                                               ],
                                               'required': [
                                                   'path',
                                               ],
                                               'nullable': [],
                                               'enum': [],
                                               'validation': []
                                           },
                                           root_map={
                                               'validations': {},
                                               'allowed_values': {},
                                               'openapi_types': {
                                                   'path': (str, ),
                                               },
                                               'attribute_map': {
                                                   'path': 'path',
                                               },
                                               'location_map': {
                                                   'path': 'path',
                                               },
                                               'collection_format_map': {}
                                           },
                                           headers_map={
                                               'accept': ['application/json'],
                                               'content_type': [],
                                           },
                                           api_client=api_client,
                                           callable=__get_pub_documents)

        def __get_spar3_documents(self, path="", **kwargs):
            """Gets SPAR3 documents and sub-directories in a directory  # noqa: E501

            This endpoint looks up all SPAR3 documents and sub-directories in a given directory.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_spar3_documents(path="", async_req=True)
            >>> result = thread.get()

            Args:
                path (str): The directory to get the documents in. defaults to "", must be one of [""]

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                DocumentDirectoriesRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['path'] = \
                path
            return self.call_with_http_info(**kwargs)

        self.get_spar3_documents = _Endpoint(settings={
            'response_type':
            dict({
                200: (DocumentDirectoriesRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/spar/v3/documents/{path}',
            'operation_id':
            'get_spar3_documents',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                             params_map={
                                                 'all': [
                                                     'path',
                                                 ],
                                                 'required': [
                                                     'path',
                                                 ],
                                                 'nullable': [],
                                                 'enum': [],
                                                 'validation': []
                                             },
                                             root_map={
                                                 'validations': {},
                                                 'allowed_values': {},
                                                 'openapi_types': {
                                                     'path': (str, ),
                                                 },
                                                 'attribute_map': {
                                                     'path': 'path',
                                                 },
                                                 'location_map': {
                                                     'path': 'path',
                                                 },
                                                 'collection_format_map': {}
                                             },
                                             headers_map={
                                                 'accept':
                                                 ['application/json'],
                                                 'content_type': [],
                                             },
                                             api_client=api_client,
                                             callable=__get_spar3_documents)

        def __get_vault_documents(self, path="", **kwargs):
            """Get Vault documents and sub-directories in a directory  # noqa: E501

            This endpoint looks up all Vault documents and sub-directories in a given directory.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_vault_documents(path="", async_req=True)
            >>> result = thread.get()

            Args:
                path (str): The directory to get the documents in. defaults to "", must be one of [""]

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                DocumentDirectoriesRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['path'] = \
                path
            return self.call_with_http_info(**kwargs)

        self.get_vault_documents = _Endpoint(settings={
            'response_type':
            dict({
                200: (DocumentDirectoriesRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/vault/v3/documents/{path}',
            'operation_id':
            'get_vault_documents',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                             params_map={
                                                 'all': [
                                                     'path',
                                                 ],
                                                 'required': [
                                                     'path',
                                                 ],
                                                 'nullable': [],
                                                 'enum': [],
                                                 'validation': []
                                             },
                                             root_map={
                                                 'validations': {},
                                                 'allowed_values': {},
                                                 'openapi_types': {
                                                     'path': (str, ),
                                                 },
                                                 'attribute_map': {
                                                     'path': 'path',
                                                 },
                                                 'location_map': {
                                                     'path': 'path',
                                                 },
                                                 'collection_format_map': {}
                                             },
                                             headers_map={
                                                 'accept':
                                                 ['application/json'],
                                                 'content_type': [],
                                             },
                                             api_client=api_client,
                                             callable=__get_vault_documents)
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __convert_pa_dates_to_absolute_format(
            self,
            enddate,
            componentid,
            account,
            **kwargs
        ):
            """Convert PA dates to absolute format  # noqa: E501

            This endpoint converts the given start and end dates in FactSet date format to yyyymmdd format for a PA calculation. For more information on FactSet date format, please refer to the PA Engine API documentation under the 'API Documentation' section in the developer portal.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.convert_pa_dates_to_absolute_format(enddate, componentid, account, async_req=True)
            >>> result = thread.get()

            Args:
                enddate (str): End Date
                componentid (str): Component Id
                account (str): Account

            Keyword Args:
                startdate (str): Start Date. [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                DateParametersSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get(
                'async_req', False
            )
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False
            )
            kwargs['_preload_content'] = kwargs.get(
                '_preload_content', True
            )
            kwargs['_request_timeout'] = kwargs.get(
                '_request_timeout', None
            )
            kwargs['_check_input_type'] = kwargs.get(
                '_check_input_type', True
            )
            kwargs['_check_return_type'] = kwargs.get(
                '_check_return_type', True
            )
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['enddate'] = \
                enddate
            kwargs['componentid'] = \
                componentid
            kwargs['account'] = \
                account
            return self.call_with_http_info(**kwargs)

        self.convert_pa_dates_to_absolute_format = _Endpoint(
            settings={
                'response_type': dict({ 200:(DateParametersSummaryRoot,),  }),
                'auth': [
                    'Basic',
                    'Bearer'
                ],
                'endpoint_path': '/analytics/engines/pa/v3/dates',
                'operation_id': 'convert_pa_dates_to_absolute_format',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'enddate',
                    'componentid',
                    'account',
                    'startdate',
                ],
                'required': [
                    'enddate',
                    'componentid',
                    'account',
                ],
                'nullable': [
                ],
                'enum': [
                ],
                'validation': [
                ]
            },
            root_map={
                'validations': {
                },
                'allowed_values': {
                },
                'openapi_types': {
                    'enddate':
                        (str,),
                    'componentid':
                        (str,),
                    'account':
                        (str,),
                    'startdate':
                        (str,),
                },
                'attribute_map': {
                    'enddate': 'enddate',
                    'componentid': 'componentid',
                    'account': 'account',
                    'startdate': 'startdate',
                },
                'location_map': {
                    'enddate': 'query',
                    'componentid': 'query',
                    'account': 'query',
                    'startdate': 'query',
                },
                'collection_format_map': {
                }
            },
            headers_map={
                'accept': [
                    'application/json'
                ],
                'content_type': [],
            },
            api_client=api_client,
            callable=__convert_pa_dates_to_absolute_format
        )

        def __convert_vault_dates_to_absolute_format(
            self,
            enddate,
            componentid,
            account,
            **kwargs
        ):
            """Convert Vault dates to absolute format  # noqa: E501

            This endpoint converts the given start and end dates in FactSet date format to yyyymmdd format for a Vault calculation. For more information on FactSet date format, please refer to the Vault API documentation under the 'API Documentation' section in the developer portal.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.convert_vault_dates_to_absolute_format(enddate, componentid, account, async_req=True)
            >>> result = thread.get()

            Args:
                enddate (str): End Date
                componentid (str): Vault Component Id
                account (str): Account

            Keyword Args:
                startdate (str): Start Date. [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                DateParametersSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get(
                'async_req', False
            )
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False
            )
            kwargs['_preload_content'] = kwargs.get(
                '_preload_content', True
            )
            kwargs['_request_timeout'] = kwargs.get(
                '_request_timeout', None
            )
            kwargs['_check_input_type'] = kwargs.get(
                '_check_input_type', True
            )
            kwargs['_check_return_type'] = kwargs.get(
                '_check_return_type', True
            )
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['enddate'] = \
                enddate
            kwargs['componentid'] = \
                componentid
            kwargs['account'] = \
                account
            return self.call_with_http_info(**kwargs)

        self.convert_vault_dates_to_absolute_format = _Endpoint(
            settings={
                'response_type': dict({ 200:(DateParametersSummaryRoot,),  }),
                'auth': [
                    'Basic',
                    'Bearer'
                ],
                'endpoint_path': '/analytics/engines/vault/v3/dates',
                'operation_id': 'convert_vault_dates_to_absolute_format',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'enddate',
                    'componentid',
                    'account',
                    'startdate',
                ],
                'required': [
                    'enddate',
                    'componentid',
                    'account',
                ],
                'nullable': [
                ],
                'enum': [
                ],
                'validation': [
                ]
            },
            root_map={
                'validations': {
                },
                'allowed_values': {
                },
                'openapi_types': {
                    'enddate':
                        (str,),
                    'componentid':
                        (str,),
                    'account':
                        (str,),
                    'startdate':
                        (str,),
                },
                'attribute_map': {
                    'enddate': 'enddate',
                    'componentid': 'componentid',
                    'account': 'account',
                    'startdate': 'startdate',
                },
                'location_map': {
                    'enddate': 'query',
                    'componentid': 'query',
                    'account': 'query',
                    'startdate': 'query',
                },
                'collection_format_map': {
                }
            },
            headers_map={
                'accept': [
                    'application/json'
                ],
                'content_type': [],
            },
            api_client=api_client,
            callable=__convert_vault_dates_to_absolute_format
        )
예제 #13
0
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __get_calculation_by_id(self, id, **kwargs):
            """Get FIAB calculation by id  # noqa: E501

            This is the endpoint to check on the progress of a previously requested calculation.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_calculation_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Run FIAB Calculation endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                FIABCalculationStatus
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_calculation_by_id = _Endpoint(
            settings={
                'response_type':
                dict({
                    200: (FIABCalculationStatus, ),
                    202: (FIABCalculationStatus, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/fiab/v1/calculations/{id}',
                'operation_id':
                'get_calculation_by_id',
                'http_method':
                'GET',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_calculation_by_id)

        def __get_calculation_status_summaries(self, **kwargs):
            """Get all FIAB calculation summaries  # noqa: E501

            This endpoints returns all FIAB calculation requests.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_calculation_status_summaries(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                {str: (FIABCalculationStatusSummary,)}
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.get_calculation_status_summaries = _Endpoint(
            settings={
                'response_type': dict({
                    200: None,
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path': '/analytics/engines/fiab/v1/calculations',
                'operation_id': 'get_calculation_status_summaries',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [],
                'required': [],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {},
                'attribute_map': {},
                'location_map': {},
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_calculation_status_summaries)

        def __run_calculation(self, **kwargs):
            """Run FIAB calculation  # noqa: E501

            This endpoint creates a new FIAB calculation.  This must be used first before get status or cancelling endpoints with a calculation id.  A successful response will contain the URL to check the status of the calculation request.    Remarks:  * Any settings in POST body will act as a one-time override over the settings saved in the FIAB template.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.run_calculation(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                fiab_calculation_parameters (FIABCalculationParameters): [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                None
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.run_calculation = _Endpoint(settings={
            'response_type': None,
            'auth': ['Basic', 'Bearer'],
            'endpoint_path': '/analytics/engines/fiab/v1/calculations',
            'operation_id': 'run_calculation',
            'http_method': 'POST',
            'servers': None,
        },
                                         params_map={
                                             'all': [
                                                 'fiab_calculation_parameters',
                                             ],
                                             'required': [],
                                             'nullable': [],
                                             'enum': [],
                                             'validation': []
                                         },
                                         root_map={
                                             'validations': {},
                                             'allowed_values': {},
                                             'openapi_types': {
                                                 'fiab_calculation_parameters':
                                                 (FIABCalculationParameters, ),
                                             },
                                             'attribute_map': {},
                                             'location_map': {
                                                 'fiab_calculation_parameters':
                                                 'body',
                                             },
                                             'collection_format_map': {}
                                         },
                                         headers_map={
                                             'accept': [],
                                             'content_type':
                                             ['application/json']
                                         },
                                         api_client=api_client,
                                         callable=__run_calculation)
예제 #14
0
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:
        vault_document_name = "Client:/aapi/VAULT_QA_PI_DEFAULT_LOCKED"
        vault_component_total_returns = "Total Returns"
        vault_component_performance = "Performance Over Time"
        vault_component_category = "Performance / Performance Relative Dates"
        vault_default_account = "CLIENT:/BISAM/REPOSITORY/QA/SMALL_PORT.ACCT"
        vault_startdate = "20180101"
        vault_enddate = "20180329"
        frequency = "Monthly"
        # 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_vault_components(
            vault_document_name)
        component_total_returns_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name ==
            vault_component_total_returns and get_components_response[0].
            data[id].category == vault_component_category
        ][0]
        print("Vault Total Returns Component Id: " +
              component_total_returns_id)

        component_performance_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name ==
            vault_component_performance and get_components_response[0].
            data[id].category == vault_component_category
        ][0]
        print("Vault Performance Over Time Component Id: " +
              component_performance_id)

        vault_account_identifier = VaultIdentifier(vault_default_account)
        vault_dates = VaultDateParameters(startdate=vault_startdate,
                                          enddate=vault_enddate,
                                          frequency=frequency)

        configurations_api = ConfigurationsApi(api_client)
        get_vault_configurations_response = configurations_api.get_vault_configurations(
            vault_default_account)
        configuration_id = list(
            get_vault_configurations_response[0].data.keys())[0]

        vault_calculation_parameters = {
            "total_returns":
            VaultCalculationParameters(componentid=component_total_returns_id,
                                       account=vault_account_identifier,
                                       dates=vault_dates,
                                       configid=configuration_id),
            "performance_over_time":
            VaultCalculationParameters(componentid=component_performance_id,
                                       account=vault_account_identifier,
                                       dates=vault_dates,
                                       configid=configuration_id)
        }

        vault_calculation_parameters_root = VaultCalculationParametersRoot(
            data=vault_calculation_parameters)

        vault_calculations_api = VaultCalculationsApi(api_client)

        post_and_calculate_response = vault_calculations_api.post_and_calculate(
            vault_calculation_parameters_root=vault_calculation_parameters_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 = vault_calculations_api.post_and_calculate(vault_calculation_parameters_root=vault_calculation_parameters_root, cache_control=cache_control)
        if post_and_calculate_response[
                1] == 202 or post_and_calculate_response[1] == 200:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = vault_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 = vault_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 = vault_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))
        else:
            print("Calculation creation failed")
            print("Error status : " + str(post_and_calculate_response[1]))
            print("Error message : " + str(post_and_calculate_response[0]))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
예제 #15
0
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)

    try:
        screeningExpressionUniverse = QuantScreeningExpressionUniverse(
            universe_expr="ISON_DOW", universe_type="Equity", security_expr="TICKER")
        fdsDate = QuantFdsDate(
            start_date="0", end_date="-5D", frequency="D", calendar="FIVEDAY")
        screeningExpression = [QuantScreeningExpression(
            expr="P_PRICE", name="Price (SCR)")]
        fqlExpression = [QuantFqlExpression(
            expr="P_PRICE", name="Price (SCR)")]

        quant_calculation_parameters = {"1": QuantCalculationParameters(screening_expression_universe=screeningExpressionUniverse,
                                        fds_date=fdsDate, screening_expression=screeningExpression, fql_expression=fqlExpression)}

        quant_calculation_parameter_root = QuantCalculationParametersRoot(
            data=quant_calculation_parameters)
        # 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"
        quant_calculations_api = QuantCalculationsApi(api_client)

        post_and_calculate_response = quant_calculations_api.post_and_calculate(
            quant_calculation_parameters_root=quant_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 = quant_calculations_api.post_and_calculate(
            # quant_calculation_parameters_root=quant_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result(post_and_calculate_response[0].read())
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = quant_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 = quant_calculations_api.get_calculation_status_by_id(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 = quant_calculations_api.get_calculation_unit_result_by_id(id=calculation_id,
                                                                                               unit_id=calculation_unit_id)
                    print("Calculation Data")
                    output_calculation_result(json.loads(result_response[0].read())['data'])
                    result_response = quant_calculations_api.get_calculation_unit_info_by_id(id=calculation_id,
                                                                                             unit_id=calculation_unit_id)
                    print("Calculation Info")
                    output_calculation_result(json.loads(result_response[0].read())['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()
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __cancel_calculation_by_id(self, id, **kwargs):
            """Cancel Quant calculation by id  # noqa: E501

            This is the endpoint to cancel a previously submitted calculation.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.cancel_calculation_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run Quant calculation endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                None
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.cancel_calculation_by_id = _Endpoint(
            settings={
                'response_type': None,
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations/{id}',
                'operation_id': 'cancel_calculation_by_id',
                'http_method': 'DELETE',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['text/plain', 'application/json', 'text/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__cancel_calculation_by_id)

        def __get_calculation_parameters(self, id, **kwargs):
            """Get Quant Engine calculation parameters by id  # noqa: E501

            This is the endpoint that returns the calculation parameters passed for a calculation.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_calculation_parameters(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run Quant Engine calculation endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                QuantCalculationParametersRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_calculation_parameters = _Endpoint(
            settings={
                'response_type': dict({
                    200: (QuantCalculationParametersRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations/{id}',
                'operation_id': 'get_calculation_parameters',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_calculation_parameters)

        def __get_calculation_status_by_id(self, id, **kwargs):
            """Get Quant Engine calculation status by id  # noqa: E501

            This is the endpoint to check on the progress of a previously requested calculation.  If the calculation has finished computing, the location header will point to the result url.  Otherwise, the calculation is still running and the X-FactSet-Api-PickUp-Progress header will contain a progress percentage.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_calculation_status_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run Quant Engine calculation endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                CalculationStatusRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_calculation_status_by_id = _Endpoint(
            settings={
                'response_type':
                dict({
                    200: (CalculationStatusRoot, ),
                    202: (CalculationStatusRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations/{id}/status',
                'operation_id':
                'get_calculation_status_by_id',
                'http_method':
                'GET',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_calculation_status_by_id)

        def __get_calculation_unit_info_by_id(self, id, unit_id, **kwargs):
            """Get Quant Engine calculation metadata information by id  # noqa: E501

            This is the endpoint to get the metadata information of a previously requested calculation.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_calculation_unit_info_by_id(id, unit_id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Get Quant calculation status by id endpoint
                unit_id (str): from url, provided from the location header in the Get Quant calculation status by id endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                file_type
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            kwargs['unit_id'] = \
                unit_id
            return self.call_with_http_info(**kwargs)

        self.get_calculation_unit_info_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    200: (file_type, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations/{id}/units/{unitId}/info',
                'operation_id': 'get_calculation_unit_info_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                    'unit_id',
                ],
                'required': [
                    'id',
                    'unit_id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                    'unit_id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                    'unit_id': 'unitId',
                },
                'location_map': {
                    'id': 'path',
                    'unit_id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': [
                    'application/json', 'application/x-protobuf',
                    'application/octet-stream'
                ],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_calculation_unit_info_by_id)

        def __get_calculation_unit_result_by_id(self, id, unit_id, **kwargs):
            """Get Quant Engine calculation result by id  # noqa: E501

            This is the endpoint to get the result of a previously requested calculation.  If the calculation has finished computing, the body of the response will contain the requested document in JSON.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_calculation_unit_result_by_id(id, unit_id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Get Quant Engine calculation status by id endpoint
                unit_id (str): from url, provided from the location header in the Get Quant Engine calculation status by id endpoint

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                file_type
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            kwargs['unit_id'] = \
                unit_id
            return self.call_with_http_info(**kwargs)

        self.get_calculation_unit_result_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    200: (file_type, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations/{id}/units/{unitId}/result',
                'operation_id': 'get_calculation_unit_result_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                    'unit_id',
                ],
                'required': [
                    'id',
                    'unit_id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                    'unit_id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                    'unit_id': 'unitId',
                },
                'location_map': {
                    'id': 'path',
                    'unit_id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': [
                    'application/json', 'application/x-protobuf',
                    'application/octet-stream'
                ],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_calculation_unit_result_by_id)

        def __post_and_calculate(self, **kwargs):
            """Create and Run Quant Engine calculation  # noqa: E501

            This endpoint runs the Quant Engine calculation specified in the POST body parameters.  It can take one or more calculation units as input.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.post_and_calculate(async_req=True)
            >>> result = thread.get()


            Keyword Args:
                cache_control (str): Standard HTTP header.  Accepts no-store, max-age, max-stale.. [optional]
                quant_calculation_parameters_root (QuantCalculationParametersRoot): [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                (For 202 status - CalculationStatusRoot)(For 201 status - ObjectRoot)(For 200 status - CalculationStatusRoot)
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            return self.call_with_http_info(**kwargs)

        self.post_and_calculate = _Endpoint(
            settings={
                'response_type':
                dict({
                    202: (CalculationStatusRoot, ),
                    201: (ObjectRoot, ),
                    200: (CalculationStatusRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations',
                'operation_id':
                'post_and_calculate',
                'http_method':
                'POST',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'cache_control',
                    'quant_calculation_parameters_root',
                ],
                'required': [],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'cache_control': (str, ),
                    'quant_calculation_parameters_root':
                    (QuantCalculationParametersRoot, ),
                },
                'attribute_map': {
                    'cache_control': 'Cache-Control',
                },
                'location_map': {
                    'cache_control': 'header',
                    'quant_calculation_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json', 'application/x-protobuf'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__post_and_calculate)

        def __put_and_calculate(self, id, **kwargs):
            """Create or update Quant Engine calculation and run it.  # noqa: E501

            This endpoint updates and runs the Quant Engine calculation specified in the PUT body parameters. This also allows creating new Quant Engine calculations with custom ids.  It can take one or more calculation units as input.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.put_and_calculate(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): from url, provided from the location header in the Create and Run Quant Engine calculation endpoint

            Keyword Args:
                cache_control (str): Standard HTTP header.  Accepts no-store, max-age, max-stale.. [optional]
                quant_calculation_parameters_root (QuantCalculationParametersRoot): Calculation Parameters. [optional]
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                (For 202 status - CalculationStatusRoot)(For 200 status - CalculationStatusRoot)(For 201 status - ObjectRoot)
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.put_and_calculate = _Endpoint(
            settings={
                'response_type':
                dict({
                    202: (CalculationStatusRoot, ),
                    200: (CalculationStatusRoot, ),
                    201: (ObjectRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path':
                '/analytics/engines/quant/v3/calculations/{id}',
                'operation_id':
                'put_and_calculate',
                'http_method':
                'PUT',
                'servers':
                None,
            },
            params_map={
                'all': [
                    'id',
                    'cache_control',
                    'quant_calculation_parameters_root',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                    'cache_control': (str, ),
                    'quant_calculation_parameters_root':
                    (QuantCalculationParametersRoot, ),
                },
                'attribute_map': {
                    'id': 'id',
                    'cache_control': 'Cache-Control',
                },
                'location_map': {
                    'id': 'path',
                    'cache_control': 'header',
                    'quant_calculation_parameters_root': 'body',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json', 'application/x-protobuf'],
                'content_type': ['application/json']
            },
            api_client=api_client,
            callable=__put_and_calculate)
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    # 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)

    try:
        screeningExpressionUniverse = QuantScreeningExpressionUniverse(
            source="ScreeningExpressionUniverse",
            universe_expr=
            "(TICKER=\"IBM\" OR TICKER=\"MS\" OR TICKER=\"GE\")=1",
            universe_type="Equity",
            security_expr="TICKER")

        fdsDate = QuantFdsDate(source="FdsDate",
                               start_date="20050701",
                               end_date="20051001",
                               frequency="M",
                               calendar="FIVEDAY")

        fqlExpression = QuantFqlExpression(source="FqlExpression",
                                           expr="P_PRICE(#DATE,#DATE,#FREQ)",
                                           name="Price")
        fqlExpression1 = QuantFqlExpression(source="FqlExpression",
                                            expr="FF_EPS(,#DATE,#DATE,#FREQ)",
                                            name="Eps")
        fqlExpression2 = QuantFqlExpression(source="FqlExpression",
                                            expr="FG_GICS_SECTOR",
                                            name="Sector")

        quant_calculation_parameters = {
            "1":
            QuantCalculationParameters(
                universe=screeningExpressionUniverse,
                dates=fdsDate,
                formulas=[fqlExpression, fqlExpression1, fqlExpression2])
        }
        # 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"
        quant_calculations_meta = QuantCalculationMeta(format='Feather')

        quant_calculation_parameter_root = QuantCalculationParametersRoot(
            data=quant_calculation_parameters, meta=quant_calculations_meta)

        quant_calculations_api = QuantCalculationsApi(api_client)

        post_and_calculate_response = quant_calculations_api.post_and_calculate(
            quant_calculation_parameters_root=quant_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 = quant_calculations_api.post_and_calculate(
        # quant_calculation_parameters_root=quant_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result('data', post_and_calculate_response[0])
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = quant_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 = quant_calculations_api.get_calculation_status_by_id(
                    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 = quant_calculations_api.get_calculation_unit_result_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    print("Calculation Data")
                    output_calculation_result('data',
                                              result_response[0].read())
                    result_response = quant_calculations_api.get_calculation_unit_info_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    print("Calculation Info")
                    output_calculation_result('info',
                                              result_response[0].read())
                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()
예제 #18
0
    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

        def __get_pa_component_by_id(self, id, **kwargs):
            """Get PA component by id  # noqa: E501

            This endpoint returns the default settings of a PA component.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_pa_component_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for a PA component

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                PAComponentRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_pa_component_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    200: (PAComponentRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path': '/analytics/engines/pa/v3/components/{id}',
                'operation_id': 'get_pa_component_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_pa_component_by_id)

        def __get_pa_components(self, document, **kwargs):
            """Get PA components  # noqa: E501

            This endpoint returns the list of PA components in a given PA document.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_pa_components(document, async_req=True)
            >>> result = thread.get()

            Args:
                document (str): Document Name

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                ComponentSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['document'] = \
                document
            return self.call_with_http_info(**kwargs)

        self.get_pa_components = _Endpoint(settings={
            'response_type':
            dict({
                200: (ComponentSummaryRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/pa/v3/components',
            'operation_id':
            'get_pa_components',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                           params_map={
                                               'all': [
                                                   'document',
                                               ],
                                               'required': [
                                                   'document',
                                               ],
                                               'nullable': [],
                                               'enum': [],
                                               'validation': []
                                           },
                                           root_map={
                                               'validations': {},
                                               'allowed_values': {},
                                               'openapi_types': {
                                                   'document': (str, ),
                                               },
                                               'attribute_map': {
                                                   'document': 'document',
                                               },
                                               'location_map': {
                                                   'document': 'query',
                                               },
                                               'collection_format_map': {}
                                           },
                                           headers_map={
                                               'accept': ['application/json'],
                                               'content_type': [],
                                           },
                                           api_client=api_client,
                                           callable=__get_pa_components)

        def __get_spar_components(self, document, **kwargs):
            """Get SPAR components  # noqa: E501

            This endpoint returns the list of SPAR components in a given SPAR document.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_spar_components(document, async_req=True)
            >>> result = thread.get()

            Args:
                document (str): Document Name

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                ComponentSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['document'] = \
                document
            return self.call_with_http_info(**kwargs)

        self.get_spar_components = _Endpoint(settings={
            'response_type':
            dict({
                200: (ComponentSummaryRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/spar/v3/components',
            'operation_id':
            'get_spar_components',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                             params_map={
                                                 'all': [
                                                     'document',
                                                 ],
                                                 'required': [
                                                     'document',
                                                 ],
                                                 'nullable': [],
                                                 'enum': [],
                                                 'validation': []
                                             },
                                             root_map={
                                                 'validations': {},
                                                 'allowed_values': {},
                                                 'openapi_types': {
                                                     'document': (str, ),
                                                 },
                                                 'attribute_map': {
                                                     'document': 'document',
                                                 },
                                                 'location_map': {
                                                     'document': 'query',
                                                 },
                                                 'collection_format_map': {}
                                             },
                                             headers_map={
                                                 'accept':
                                                 ['application/json'],
                                                 'content_type': [],
                                             },
                                             api_client=api_client,
                                             callable=__get_spar_components)

        def __get_vault_component_by_id(self, id, **kwargs):
            """Get Vault component by id  # noqa: E501

            This endpoint returns the default settings of a Vault component.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_vault_component_by_id(id, async_req=True)
            >>> result = thread.get()

            Args:
                id (str): Unique identifier for a vault component

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                VaultComponentRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['id'] = \
                id
            return self.call_with_http_info(**kwargs)

        self.get_vault_component_by_id = _Endpoint(
            settings={
                'response_type': dict({
                    200: (VaultComponentRoot, ),
                }),
                'auth': ['Basic', 'Bearer'],
                'endpoint_path': '/analytics/engines/vault/v3/components/{id}',
                'operation_id': 'get_vault_component_by_id',
                'http_method': 'GET',
                'servers': None,
            },
            params_map={
                'all': [
                    'id',
                ],
                'required': [
                    'id',
                ],
                'nullable': [],
                'enum': [],
                'validation': []
            },
            root_map={
                'validations': {},
                'allowed_values': {},
                'openapi_types': {
                    'id': (str, ),
                },
                'attribute_map': {
                    'id': 'id',
                },
                'location_map': {
                    'id': 'path',
                },
                'collection_format_map': {}
            },
            headers_map={
                'accept': ['application/json'],
                'content_type': [],
            },
            api_client=api_client,
            callable=__get_vault_component_by_id)

        def __get_vault_components(self, document, **kwargs):
            """Get Vault components  # noqa: E501

            This endpoint returns the list of Vault components in a given Vault document.  # noqa: E501
            This method makes a synchronous HTTP request by default. To make an
            asynchronous HTTP request, please pass async_req=True

            >>> thread = api.get_vault_components(document, async_req=True)
            >>> result = thread.get()

            Args:
                document (str): Document Name

            Keyword Args:
                _return_http_data_only (bool): response data without head status
                    code and headers. Default is False.
                _preload_content (bool): if False, the urllib3.HTTPResponse object
                    will be returned without reading/decoding response data.
                    Default is True.
                _request_timeout (float/tuple): timeout setting for this request. If one
                    number provided, it will be total request timeout. It can also
                    be a pair (tuple) of (connection, read) timeouts.
                    Default is None.
                _check_input_type (bool): specifies if type checking
                    should be done one the data sent to the server.
                    Default is True.
                _check_return_type (bool): specifies if type checking
                    should be done one the data received from the server.
                    Default is True.
                _host_index (int/None): specifies the index of the server
                    that we want to use.
                    Default is read from the configuration.
                async_req (bool): execute request asynchronously

            Returns:
                ComponentSummaryRoot
                    If the method is called asynchronously, returns the request
                    thread.
            """
            kwargs['async_req'] = kwargs.get('async_req', False)
            kwargs['_return_http_data_only'] = kwargs.get(
                '_return_http_data_only', False)
            kwargs['_preload_content'] = kwargs.get('_preload_content', True)
            kwargs['_request_timeout'] = kwargs.get('_request_timeout', None)
            kwargs['_check_input_type'] = kwargs.get('_check_input_type', True)
            kwargs['_check_return_type'] = kwargs.get('_check_return_type',
                                                      True)
            kwargs['_host_index'] = kwargs.get('_host_index')
            kwargs['document'] = \
                document
            return self.call_with_http_info(**kwargs)

        self.get_vault_components = _Endpoint(settings={
            'response_type':
            dict({
                200: (ComponentSummaryRoot, ),
            }),
            'auth': ['Basic', 'Bearer'],
            'endpoint_path':
            '/analytics/engines/vault/v3/components',
            'operation_id':
            'get_vault_components',
            'http_method':
            'GET',
            'servers':
            None,
        },
                                              params_map={
                                                  'all': [
                                                      'document',
                                                  ],
                                                  'required': [
                                                      'document',
                                                  ],
                                                  'nullable': [],
                                                  'enum': [],
                                                  'validation': []
                                              },
                                              root_map={
                                                  'validations': {},
                                                  'allowed_values': {},
                                                  'openapi_types': {
                                                      'document': (str, ),
                                                  },
                                                  'attribute_map': {
                                                      'document': 'document',
                                                  },
                                                  'location_map': {
                                                      'document': 'query',
                                                  },
                                                  'collection_format_map': {}
                                              },
                                              headers_map={
                                                  'accept':
                                                  ['application/json'],
                                                  'content_type': [],
                                              },
                                              api_client=api_client,
                                              callable=__get_vault_components)
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)

    try:
        # {
        #     "strategy": {
        #         "id": "Client:/analytics_api/dbui_simple_strategy"
        #     },
        #     "account": {
        #         "id": "CLIENT:/FPO/1K_MAC_AMZN_AAPL.ACCT",
        #         "padocument": {
        #             "id": "CLIENT:/FPO/FPO_MASTER"
        #         }
        #     },
        #     "optimization": {
        #         "riskmodeldate": "0M",
        #         "backtestdate": "0M"
        #     },
        #     "outputtypes": {
        #         "trades": {
        #             "identifiertype": "Asset",
        #             "includecash": false
        #         }
        #     }
        # }
        # 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"
        fpo_optimizer_strategy = FPOOptimizerStrategy(
            id="Client:/analytics_api/dbui_simple_strategy")
        fpo_pa_doc = PaDoc("CLIENT:/FPO/FPO_MASTER")
        fpo_optimizer_account = FPOAccount(
            fpo_pa_doc, id="CLIENT:/FPO/1K_MAC_AMZN_AAPL.ACCT")
        fpo_optimizer_optimization = Optimization(
            risk_model_date="0M",
            backtest_date="0M",
        )
        fpo_optimizer_trades_list = OptimizerTradesList(
            identifier_type="Asset", include_cash=False)
        fpo_optimizer_output_types = OptimizerOutputTypes(
            trades=fpo_optimizer_trades_list)
        fpo_optimizer_parameters = FPOOptimizationParameters(
            fpo_optimizer_strategy,
            fpo_optimizer_output_types,
            account=fpo_optimizer_account,
            optimization=fpo_optimizer_optimization
        )
        fpo_optimization_parameters_root = FPOOptimizationParametersRoot(
            data=fpo_optimizer_parameters)

        fpo_optimizations_api = FPOOptimizerApi(api_client)

        post_and_optimize_response = fpo_optimizations_api.post_and_optimize(
            fpo_optimization_parameters_root=fpo_optimization_parameters_root
        )
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_optimize_response = fpo_optimizations_api.post_and_optimize(
            # fpo_optimization_parameters_root=fpo_optimization_parameters_root, cache_control=cache_control
        # )
        if post_and_optimize_response[1] == 201:
            output_optimization_result(post_and_optimize_response[0]['data'])
        else:
            optimization_id = post_and_optimize_response[2]["X-Factset-Api-Calculation-Id"]
            print("Calculation Id: " + optimization_id)

            status_response = fpo_optimizations_api.get_optimization_status_by_id(id=optimization_id)

            while status_response[1] == 202:
                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 = fpo_optimizations_api.get_optimization_status_by_id(optimization_id)

            if status_response[1] == 201:
                print("Optimization Id: " + optimization_id + " Succeeded!!!")
                result_response = fpo_optimizations_api.get_optimization_result(id=optimization_id)
                output_optimization_result(result_response[0]['data'])
            else:
                print("Optimization Id:" + optimization_id + " Failed!!!")
                print("Error message : " + status_response[0].errors)

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
spar_benchmark_russell_pr_2000 = "RUSSELL_P:R.2000"
spar_benchmark_russell_prefix = "RUSSELL"
spar_benchmark_russell_return_type = "GTR"
startdate = "20180101"
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)