PA Batch API (Retiring by 10/31/19)

Overview

Through the PA Batch API, request analytics in larger capacities, including the flexibility of requesting multiple portfolios, benchmarks, and return periods.

API Definition

swagger_file_format

API Documentation

SDK Library

Code Snippet

Building and running a batch
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;

using FactSet.AnalyticsAPI.PABatchAPI.v1.Api;
using FactSet.AnalyticsAPI.PABatchAPI.v1.Client;
using FactSet.AnalyticsAPI.PABatchAPI.v1.Model;
using FactSet.AnalyticsAPI.PAEngineAPI.v1.Api;
using FactSet.AnalyticsAPI.PAEngineAPI.v1.Model;
using FactSet.Protobuf.Stach;
using Google.Protobuf;

namespace FactSet.AnalyticsAPI.PABatchAPI.v1.Examples
{
    class Program
    {
        private static Configuration paBatchApiConfiguration;
        private static PAEngineAPI.v1.Client.Configuration paEngineApiConfiguration;
        private const string BASE_PATH = "https://api.factset.com";
        private const string USERNAME = "<username-serial>";
        private const string PASSWORD = "<apiKey>";

        private static Configuration GetPaBatchApiConfiguration()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (paBatchApiConfiguration != null)
            {
                return paBatchApiConfiguration;
            }

            paBatchApiConfiguration = new Configuration
            {
                BasePath = BASE_PATH,
                Username = USERNAME,
                Password = PASSWORD
            };

            return paBatchApiConfiguration;
        }

        private static PAEngineAPI.v1.Client.Configuration GetPaEngineApiConfiguration()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (paBatchApiConfiguration != null)
            {
                return paEngineApiConfiguration;
            }

            paEngineApiConfiguration = new PAEngineAPI.v1.Client.Configuration
            {
                BasePath = BASE_PATH,
                Username = USERNAME,
                Password = PASSWORD
            };

            return paEngineApiConfiguration;
        }

        static void Main(string[] args)
        {
            try
            {
                var componentsApi = new ComponentsApi(GetPaEngineApiConfiguration());

                // PA_DOCUMENTS:DEFAULT is default document available to all users.
                PAEngineAPI.v1.Client.ApiResponse<Dictionary<string, ComponentListEntity>> componentGetAllResponse =
                    componentsApi.GetAllWithHttpInfo("PA_DOCUMENTS:DEFAULT");

                if (componentGetAllResponse.StatusCode != 200)
                {
                    LogError(componentGetAllResponse);
                    return;
                }

                var componentId = componentGetAllResponse.Data.First().Key;

                var accounts = new List<string> { "BENCH:SP50", "BENCH:R.1000" };
                var benchmarks = new List<string> { "BENCH:R.1000" };
                var dates = new Model.DateParameters()
                {
                    Startdate = "-2M",
                    Enddate = "0",
                    Frequency = Model.DateParameters.FrequencyEnum.Monthly
                };

                var inputBody = new List<Model.CalculationParameters>
                {
                    new Model.CalculationParameters(componentId, accounts, benchmarks, dates),
                    new Model.CalculationParameters(componentId, accounts, benchmarks)
                };
                var batchApi = new BatchApi(GetPaBatchApiConfiguration());
                var createResponse = batchApi.CreateWithHttpInfo(inputBody);

                if (createResponse.StatusCode != 202)
                {
                    LogError(createResponse);
                    return;
                }

                // Parse the the Location header for calculation Id
                createResponse.Headers.TryGetValue("Location", out string location);
                if (string.IsNullOrWhiteSpace(location))
                {
                    LogError(createResponse);
                    return;
                }

                var calculationId = location.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries).Last();
                ApiResponse<BatchCalculationParameters> getStatus = null;

                while (getStatus == null || getStatus.Data.Status == BatchCalculationParameters.StatusEnum.Queued ||
                       getStatus.Data.Status == BatchCalculationParameters.StatusEnum.Executing)
                {
                    if (getStatus != null && getStatus.Headers.ContainsKey("Cache-Control"))
                    {
                        var ageValue = getStatus.Headers["Cache-Control"];
                        if (string.IsNullOrWhiteSpace(ageValue))
                        {
                            Console.WriteLine("Sleeping for 2 seconds");
                            // Sleep for atleast 2 seconds.
                            Thread.Sleep(2000);
                        }
                        else
                        {
                            int age = int.Parse(ageValue.Replace("max-age=", ""));
                            Console.WriteLine($"Sleeping for {age} seconds");
                            Thread.Sleep(age * 1000);
                        }
                    }

                    getStatus = batchApi.GetStatusByIdWithHttpInfo(calculationId);
                }

                Console.WriteLine("Batch Completed!!!");

                foreach (var calculationParameters in getStatus.Data.Calculations.Where(w =>
                        w.Value.Status == CalculationCalculationParameters.StatusEnum.Failed))
                {
                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Failed!!!");
                    Console.WriteLine("Error message : " + calculationParameters.Value.Error);
                }

                foreach (var calculationParameters in getStatus.Data.Calculations.Where(w =>
                    w.Value.Status == CalculationCalculationParameters.StatusEnum.Success))
                {
                    var resultResponse = batchApi.GetByUrlWithHttpInfo(calculationParameters.Value.Result);
                    if (resultResponse.StatusCode != 200)
                    {
                        LogError(resultResponse);
                        return;
                    }

                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Succeeded!!!");

                    JsonParser.Settings jpSettings = JsonParser.Settings.Default;
                    JsonParser jp = new JsonParser(jpSettings.WithIgnoreUnknownFields(true));
                    var package = jp.Parse<Package>(resultResponse.Data);

                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Result");
                    Console.WriteLine(package.ToString());
                }

                Console.ReadKey();
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error!!!");
                Console.WriteLine("Error Code: " + e.ErrorCode);
                Console.WriteLine(e.ErrorContent);
            }
        }

        private static void LogError<T>(ApiResponse<T> response)
        {
            Console.WriteLine("Error!!!");
            Console.WriteLine("Status Code: " + response.StatusCode);
            Console.WriteLine("Request Key: " + response.Headers["X-Factset-Api-Request-Key"]);
        }

        private static void LogError<T>(PAEngineAPI.v1.Client.ApiResponse<T> response)
        {
            Console.WriteLine("Error!!!");
            Console.WriteLine("Status Code: " + response.StatusCode);
            Console.WriteLine("Request Key: " + response.Headers["X-Factset-Api-Request-Key"]);
        }
    }
}

 

package examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;

import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.InvalidProtocolBufferException;
import com.factset.protobuf.stach.PackageProto.Package.Builder;
import com.factset.protobuf.stach.PackageProto.Package;

import factset.analyticsapi.pabatchapi.v1.ApiClient;
import factset.analyticsapi.pabatchapi.v1.ApiException;
import factset.analyticsapi.pabatchapi.v1.ApiResponse;
import factset.analyticsapi.pabatchapi.v1.api.BatchApi;
import factset.analyticsapi.paengineapi.v1.api.ComponentsApi;
import factset.analyticsapi.paengineapi.v1.models.ComponentListEntity;
import factset.analyticsapi.pabatchapi.v1.models.*;

public class Example {
	private static ApiClient apiPaBatchClient = null;
	private static factset.analyticsapi.paengineapi.v1.ApiClient apiPaEngineClient = null;
	private static final String BASE_PATH = "https://api.factset.com";
	private static final String USERNAME = "<username-serial>";
	private static final String PASSWORD = "<apiKey>";

	public static void main(String[] args) throws InterruptedException {
		try {
			ComponentsApi componentsApi = new ComponentsApi(apiPaEngineClientFactory());
			Map<String, ComponentListEntity> components = componentsApi.getAll("PA_DOCUMENTS:DEFAULT");
			String componentId = components.entrySet().stream().findFirst().get().getKey();
			System.out.println("ComponentID: " + componentId);

			CalculationParameters parameters = new CalculationParameters();
			parameters.componentid(componentId);
			parameters.setAccounts(Arrays.asList("BENCH:SP50", "BENCH:R.1000"));
			parameters.setBenchmarks(Arrays.asList("BENCH:R.1000"));
			
			DateParameters dates = new DateParameters();
			dates.setStartdate("-2M");
			dates.setEnddate("0");
			dates.setFrequency(DateParameters.FrequencyEnum.MONTHLY);
			parameters.dates(dates);

			List<CalculationParameters> parametersList = new ArrayList<CalculationParameters>();
			parametersList.add(parameters);
			parametersList.add(parameters);

			BatchApi batchApi = new BatchApi(apiPaBatchClientFactory());
			ApiResponse<Void> calculationResult = batchApi.createWithHttpInfo(parametersList);

			Map<String, List<String>> headers = calculationResult.getHeaders();
			String locationToPoll = headers.get("Location").get(0);
			String[] splits = locationToPoll.split("/");
			String requestId = splits[splits.length - 1];

			ApiResponse<BatchCalculationParameters> getStatus = null;

			while (getStatus == null 
					|| getStatus.getData().getStatus() == BatchCalculationParameters.StatusEnum.QUEUED 
					|| getStatus.getData().getStatus() == BatchCalculationParameters.StatusEnum.EXECUTING) {
      			if(getStatus != null) {
					List<String> cacheControl = getStatus.getHeaders().get("Cache-Control");
					if (cacheControl != null) {
						int maxAge = Integer.parseInt(cacheControl.get(0).replaceAll("max-age=", ""));
						System.out.println("Sleeping for: " + maxAge + " seconds");
						Thread.sleep(maxAge * 1000);
					} else {
						System.out.println("Sleeping for: 2 seconds");
						Thread.sleep(2 * 1000);
					}
				}
				getStatus = batchApi.getStatusByIdWithHttpInfo(requestId);
			}
      
			System.out.println("Batch Completed!!!");

			for (Map.Entry<String, CalculationCalculationParameters> calculationParameters : getStatus.getData().getCalculations().entrySet()) {
				if (calculationParameters.getValue().getStatus() == CalculationCalculationParameters.StatusEnum.FAILED) {
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Failed!!!");
					System.out.println("Error message : " + calculationParameters.getValue().getError());
				}
			}

			for (Map.Entry<String, CalculationCalculationParameters> calculationParameters : getStatus.getData().getCalculations().entrySet()) {
				if (calculationParameters.getValue().getStatus() == CalculationCalculationParameters.StatusEnum.SUCCESS) {
					ApiResponse<String> resultResponse = batchApi.getByUrlWithHttpInfo(calculationParameters.getValue().getResult());
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Succeeded!!!");
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Result");
					
					Builder builder = Package.newBuilder();
					try {
						JsonFormat.parser().ignoringUnknownFields().merge(resultResponse.getData(), builder);
					} catch (InvalidProtocolBufferException e) {
						System.out.println("Error while deserializing the response");
						e.printStackTrace();
					}

					Package result = (Package) builder.build();
					System.out.println(result.toString()); // To print the result object as a JSON
				}
			}
		} catch (ApiException e) {
			System.err.println("ResponseBody: " + e.getResponseBody());
			System.err.println(
					"X-DataDirect-Request-Key: " + e.getResponseHeaders().get("X-DataDirect-Request-Key").get(0));
			e.printStackTrace();
		} catch (factset.analyticsapi.paengineapi.v1.ApiException e) {
			System.err.println("ResponseBody: " + e.getResponseBody());
			System.err.println(
					"X-DataDirect-Request-Key: " + e.getResponseHeaders().get("X-DataDirect-Request-Key").get(0));
			e.printStackTrace();
		}
	}

	private static ApiClient apiPaBatchClientFactory() {
		if (apiPaBatchClient != null) {
			return apiPaBatchClient;
		}

		apiPaBatchClient = new ApiClient();
		apiPaBatchClient.setBasePath(BASE_PATH);
		apiPaBatchClient.setUsername(USERNAME); // username-serial combination
		apiPaBatchClient.setPassword(PASSWORD); // api key

		apiPaBatchClient.setVerifyingSsl(false);

		return apiPaBatchClient;
	}

	private static factset.analyticsapi.paengineapi.v1.ApiClient apiPaEngineClientFactory() {
		if (apiPaEngineClient != null) {
			return apiPaEngineClient;
		}

		apiPaEngineClient = new factset.analyticsapi.paengineapi.v1.ApiClient();
		apiPaEngineClient.setBasePath(BASE_PATH);
		apiPaEngineClient.setUsername(USERNAME); // username-serial combination
		apiPaEngineClient.setPassword(PASSWORD); // api key

		apiPaEngineClient.setVerifyingSsl(false);

		return apiPaEngineClient;
	}
}

 

import time
import json

from google.protobuf.json_format import MessageToJson
from google.protobuf.json_format import MessageToDict

from fds.protobuf.stach.Package_pb2 import Package
from google.protobuf import json_format

from fds.analyticsapi.paengineapi.v1.configuration import Configuration as PaEngineConfiguration
from fds.analyticsapi.paengineapi.v1.api_client import ApiClient as PaEngineApiClient
from fds.analyticsapi.paengineapi.v1.api.components_api import ComponentsApi
from fds.analyticsapi.paengineapi.v1.models.component_entity import ComponentEntity

from fds.analyticsapi.pabatchapi.v1.configuration import Configuration as PaBatchConfiguration
from fds.analyticsapi.pabatchapi.v1.api_client import ApiClient as PaBatchApiClient
from fds.analyticsapi.pabatchapi.v1.api.batch_api import BatchApi
from fds.analyticsapi.pabatchapi.v1.models.calculation_parameters import CalculationParameters
from fds.analyticsapi.pabatchapi.v1.models.date_parameters import DateParameters


host = "https://api.factset.com"
username = "<username-serial>"
password = "<apiKey>"
verify_ssl = False

pa_batch_config = PaBatchConfiguration()
pa_batch_config.host = host
pa_batch_config.username = username
pa_batch_config.password = password
pa_batch_config.verify_ssl = False

pa_engine_config = PaEngineConfiguration()
pa_engine_config.host = host
pa_engine_config.username = username
pa_engine_config.password = password
pa_engine_config.verify_ssl = False

pa_batch_api_client = PaBatchApiClient(pa_batch_config)
pa_engine_api_client = PaEngineApiClient(pa_engine_config)

document_name="PA_DOCUMENTS:DEFAULT"
accounts = ["BENCH:SP50", "BENCH:R.1000"]
benchmarks = ["BENCH:R.2000"]
dates = DateParameters()
dates.startdate = "-2M"
dates.enddate = "0"
dates.frequency = "Monthly"

components_api = ComponentsApi(pa_engine_api_client)
component_api_get_result = components_api.get_all_with_http_info(document_name)
component_id = list(component_api_get_result[0].keys())[0]
print("Component ID: " + component_id)

calculation_parameters_list = [CalculationParameters(component_id, accounts, benchmarks, dates), CalculationParameters(component_id, accounts, benchmarks)]
batch_api = BatchApi(pa_batch_api_client)
batch_api_post_result =  batch_api.create_with_http_info(calculation_parameters_list=calculation_parameters_list)

if(batch_api_post_result[1] != 202):
    print(batch_api_post_result[2].get("x-datadirect-request-key"))
    quit()

status_location = batch_api_post_result[2].get("location")
splits = status_location.split("/")
batch_id = splits[-1]
print("Batch Id: " + batch_id)

batch_status = batch_api.get_status_by_id_with_http_info(batch_id)
while (batch_status[1] == 200 and (batch_status[0].status == "Queued" or batch_status[0].status == "Executing")):
    age_value = batch_status[2].get("cache-control")
    if(age_value != None):
        max_age = age_value.replace("max-age=", "")
        print('Sleeping: ' + max_age)
        time.sleep(int(max_age))
    batch_status = batch_api.get_status_by_id_with_http_info(batch_id)

if(batch_status[1] != 200):
    print(batch_status[2].get("x-datadirect-request-key"))
    quit()

for calculation_id, calculation_details in batch_status[0].calculations.items(): 
    if calculation_details.status == "Failed":
        print("CalculationId : " + calculation_id + " Failed!!!")
        print("Error message : " + calculation_details.error)

for calculation_id, calculation_details in batch_status[0].calculations.items(): 
    if calculation_details.status == "Success":
        batch_calculation_result = batch_api.get_by_url_with_http_info(calculation_details.result)
        
        if(batch_calculation_result[1] != 200):
            print(batch_calculation_result[2].get('x-datadirect-request-key'))
            quit()
        
        result =  json_format.Parse(json.dumps(batch_calculation_result[0]), Package())
        print(MessageToJson(result)) # To print the result object as a JSON
        #print(MessageToDict(result)) # To print the result object as a Dictionary

 

Building and running a batch
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;

using FactSet.AnalyticsAPI.PABatchAPI.v1.Api;
using FactSet.AnalyticsAPI.PABatchAPI.v1.Client;
using FactSet.AnalyticsAPI.PABatchAPI.v1.Model;
using FactSet.AnalyticsAPI.PAEngineAPI.v1.Api;
using FactSet.AnalyticsAPI.PAEngineAPI.v1.Model;
using FactSet.Protobuf.Stach;
using Google.Protobuf;

namespace FactSet.AnalyticsAPI.PABatchAPI.v1.Examples
{
    class Program
    {
        private static Configuration paBatchApiConfiguration;
        private static PAEngineAPI.v1.Client.Configuration paEngineApiConfiguration;
        private const string BASE_PATH = "https://api.factset.com";
        private const string USERNAME = "<username-serial>";
        private const string PASSWORD = "<apiKey>";

        private static Configuration GetPaBatchApiConfiguration()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (paBatchApiConfiguration != null)
            {
                return paBatchApiConfiguration;
            }

            paBatchApiConfiguration = new Configuration
            {
                BasePath = BASE_PATH,
                Username = USERNAME,
                Password = PASSWORD
            };

            return paBatchApiConfiguration;
        }

        private static PAEngineAPI.v1.Client.Configuration GetPaEngineApiConfiguration()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (paBatchApiConfiguration != null)
            {
                return paEngineApiConfiguration;
            }

            paEngineApiConfiguration = new PAEngineAPI.v1.Client.Configuration
            {
                BasePath = BASE_PATH,
                Username = USERNAME,
                Password = PASSWORD
            };

            return paEngineApiConfiguration;
        }

        static void Main(string[] args)
        {
            try
            {
                var componentsApi = new ComponentsApi(GetPaEngineApiConfiguration());

                // PA_DOCUMENTS:DEFAULT is default document available to all users.
                PAEngineAPI.v1.Client.ApiResponse<Dictionary<string, ComponentListEntity>> componentGetAllResponse =
                    componentsApi.GetAllWithHttpInfo("PA_DOCUMENTS:DEFAULT");

                if (componentGetAllResponse.StatusCode != 200)
                {
                    LogError(componentGetAllResponse);
                    return;
                }

                var componentId = componentGetAllResponse.Data.First().Key;

                var accounts = new List<string> { "BENCH:SP50", "BENCH:R.1000" };
                var benchmarks = new List<string> { "BENCH:R.1000" };
                var dates = new Model.DateParameters()
                {
                    Startdate = "-2M",
                    Enddate = "0",
                    Frequency = Model.DateParameters.FrequencyEnum.Monthly
                };

                var inputBody = new List<Model.CalculationParameters>
                {
                    new Model.CalculationParameters(componentId, accounts, benchmarks, dates),
                    new Model.CalculationParameters(componentId, accounts, benchmarks)
                };
                var batchApi = new BatchApi(GetPaBatchApiConfiguration());
                var createResponse = batchApi.CreateWithHttpInfo(inputBody);

                if (createResponse.StatusCode != 202)
                {
                    LogError(createResponse);
                    return;
                }

                // Parse the the Location header for calculation Id
                createResponse.Headers.TryGetValue("Location", out string location);
                if (string.IsNullOrWhiteSpace(location))
                {
                    LogError(createResponse);
                    return;
                }

                var calculationId = location.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries).Last();
                ApiResponse<BatchCalculationParameters> getStatus = null;

                while (getStatus == null || getStatus.Data.Status == BatchCalculationParameters.StatusEnum.Queued ||
                       getStatus.Data.Status == BatchCalculationParameters.StatusEnum.Executing)
                {
                    if (getStatus != null && getStatus.Headers.ContainsKey("Cache-Control"))
                    {
                        var ageValue = getStatus.Headers["Cache-Control"];
                        if (string.IsNullOrWhiteSpace(ageValue))
                        {
                            Console.WriteLine("Sleeping for 2 seconds");
                            // Sleep for atleast 2 seconds.
                            Thread.Sleep(2000);
                        }
                        else
                        {
                            int age = int.Parse(ageValue.Replace("max-age=", ""));
                            Console.WriteLine($"Sleeping for {age} seconds");
                            Thread.Sleep(age * 1000);
                        }
                    }

                    getStatus = batchApi.GetStatusByIdWithHttpInfo(calculationId);
                }

                Console.WriteLine("Batch Completed!!!");

                foreach (var calculationParameters in getStatus.Data.Calculations.Where(w =>
                        w.Value.Status == CalculationCalculationParameters.StatusEnum.Failed))
                {
                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Failed!!!");
                    Console.WriteLine("Error message : " + calculationParameters.Value.Error);
                }

                foreach (var calculationParameters in getStatus.Data.Calculations.Where(w =>
                    w.Value.Status == CalculationCalculationParameters.StatusEnum.Success))
                {
                    var resultResponse = batchApi.GetByUrlWithHttpInfo(calculationParameters.Value.Result);
                    if (resultResponse.StatusCode != 200)
                    {
                        LogError(resultResponse);
                        return;
                    }

                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Succeeded!!!");

                    JsonParser.Settings jpSettings = JsonParser.Settings.Default;
                    JsonParser jp = new JsonParser(jpSettings.WithIgnoreUnknownFields(true));
                    var package = jp.Parse<Package>(resultResponse.Data);

                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Result");
                    Console.WriteLine(package.ToString());
                }

                Console.ReadKey();
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error!!!");
                Console.WriteLine("Error Code: " + e.ErrorCode);
                Console.WriteLine(e.ErrorContent);
            }
        }

        private static void LogError<T>(ApiResponse<T> response)
        {
            Console.WriteLine("Error!!!");
            Console.WriteLine("Status Code: " + response.StatusCode);
            Console.WriteLine("Request Key: " + response.Headers["X-Factset-Api-Request-Key"]);
        }

        private static void LogError<T>(PAEngineAPI.v1.Client.ApiResponse<T> response)
        {
            Console.WriteLine("Error!!!");
            Console.WriteLine("Status Code: " + response.StatusCode);
            Console.WriteLine("Request Key: " + response.Headers["X-Factset-Api-Request-Key"]);
        }
    }
}

 

package examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;

import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.InvalidProtocolBufferException;
import com.factset.protobuf.stach.PackageProto.Package.Builder;
import com.factset.protobuf.stach.PackageProto.Package;

import factset.analyticsapi.pabatchapi.v1.ApiClient;
import factset.analyticsapi.pabatchapi.v1.ApiException;
import factset.analyticsapi.pabatchapi.v1.ApiResponse;
import factset.analyticsapi.pabatchapi.v1.api.BatchApi;
import factset.analyticsapi.paengineapi.v1.api.ComponentsApi;
import factset.analyticsapi.paengineapi.v1.models.ComponentListEntity;
import factset.analyticsapi.pabatchapi.v1.models.*;

public class Example {
	private static ApiClient apiPaBatchClient = null;
	private static factset.analyticsapi.paengineapi.v1.ApiClient apiPaEngineClient = null;
	private static final String BASE_PATH = "https://api.factset.com";
	private static final String USERNAME = "<username-serial>";
	private static final String PASSWORD = "<apiKey>";

	public static void main(String[] args) throws InterruptedException {
		try {
			ComponentsApi componentsApi = new ComponentsApi(apiPaEngineClientFactory());
			Map<String, ComponentListEntity> components = componentsApi.getAll("PA_DOCUMENTS:DEFAULT");
			String componentId = components.entrySet().stream().findFirst().get().getKey();
			System.out.println("ComponentID: " + componentId);

			CalculationParameters parameters = new CalculationParameters();
			parameters.componentid(componentId);
			parameters.setAccounts(Arrays.asList("BENCH:SP50", "BENCH:R.1000"));
			parameters.setBenchmarks(Arrays.asList("BENCH:R.1000"));
			
			DateParameters dates = new DateParameters();
			dates.setStartdate("-2M");
			dates.setEnddate("0");
			dates.setFrequency(DateParameters.FrequencyEnum.MONTHLY);
			parameters.dates(dates);

			List<CalculationParameters> parametersList = new ArrayList<CalculationParameters>();
			parametersList.add(parameters);
			parametersList.add(parameters);

			BatchApi batchApi = new BatchApi(apiPaBatchClientFactory());
			ApiResponse<Void> calculationResult = batchApi.createWithHttpInfo(parametersList);

			Map<String, List<String>> headers = calculationResult.getHeaders();
			String locationToPoll = headers.get("Location").get(0);
			String[] splits = locationToPoll.split("/");
			String requestId = splits[splits.length - 1];

			ApiResponse<BatchCalculationParameters> getStatus = null;

			while (getStatus == null 
					|| getStatus.getData().getStatus() == BatchCalculationParameters.StatusEnum.QUEUED 
					|| getStatus.getData().getStatus() == BatchCalculationParameters.StatusEnum.EXECUTING) {
      			if(getStatus != null) {
					List<String> cacheControl = getStatus.getHeaders().get("Cache-Control");
					if (cacheControl != null) {
						int maxAge = Integer.parseInt(cacheControl.get(0).replaceAll("max-age=", ""));
						System.out.println("Sleeping for: " + maxAge + " seconds");
						Thread.sleep(maxAge * 1000);
					} else {
						System.out.println("Sleeping for: 2 seconds");
						Thread.sleep(2 * 1000);
					}
				}
				getStatus = batchApi.getStatusByIdWithHttpInfo(requestId);
			}
      
			System.out.println("Batch Completed!!!");

			for (Map.Entry<String, CalculationCalculationParameters> calculationParameters : getStatus.getData().getCalculations().entrySet()) {
				if (calculationParameters.getValue().getStatus() == CalculationCalculationParameters.StatusEnum.FAILED) {
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Failed!!!");
					System.out.println("Error message : " + calculationParameters.getValue().getError());
				}
			}

			for (Map.Entry<String, CalculationCalculationParameters> calculationParameters : getStatus.getData().getCalculations().entrySet()) {
				if (calculationParameters.getValue().getStatus() == CalculationCalculationParameters.StatusEnum.SUCCESS) {
					ApiResponse<String> resultResponse = batchApi.getByUrlWithHttpInfo(calculationParameters.getValue().getResult());
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Succeeded!!!");
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Result");
					
					Builder builder = Package.newBuilder();
					try {
						JsonFormat.parser().ignoringUnknownFields().merge(resultResponse.getData(), builder);
					} catch (InvalidProtocolBufferException e) {
						System.out.println("Error while deserializing the response");
						e.printStackTrace();
					}

					Package result = (Package) builder.build();
					System.out.println(result.toString()); // To print the result object as a JSON
				}
			}
		} catch (ApiException e) {
			System.err.println("ResponseBody: " + e.getResponseBody());
			System.err.println(
					"X-DataDirect-Request-Key: " + e.getResponseHeaders().get("X-DataDirect-Request-Key").get(0));
			e.printStackTrace();
		} catch (factset.analyticsapi.paengineapi.v1.ApiException e) {
			System.err.println("ResponseBody: " + e.getResponseBody());
			System.err.println(
					"X-DataDirect-Request-Key: " + e.getResponseHeaders().get("X-DataDirect-Request-Key").get(0));
			e.printStackTrace();
		}
	}

	private static ApiClient apiPaBatchClientFactory() {
		if (apiPaBatchClient != null) {
			return apiPaBatchClient;
		}

		apiPaBatchClient = new ApiClient();
		apiPaBatchClient.setBasePath(BASE_PATH);
		apiPaBatchClient.setUsername(USERNAME); // username-serial combination
		apiPaBatchClient.setPassword(PASSWORD); // api key

		apiPaBatchClient.setVerifyingSsl(false);

		return apiPaBatchClient;
	}

	private static factset.analyticsapi.paengineapi.v1.ApiClient apiPaEngineClientFactory() {
		if (apiPaEngineClient != null) {
			return apiPaEngineClient;
		}

		apiPaEngineClient = new factset.analyticsapi.paengineapi.v1.ApiClient();
		apiPaEngineClient.setBasePath(BASE_PATH);
		apiPaEngineClient.setUsername(USERNAME); // username-serial combination
		apiPaEngineClient.setPassword(PASSWORD); // api key

		apiPaEngineClient.setVerifyingSsl(false);

		return apiPaEngineClient;
	}
}

 

import time
import json

from google.protobuf.json_format import MessageToJson
from google.protobuf.json_format import MessageToDict

from fds.protobuf.stach.Package_pb2 import Package
from google.protobuf import json_format

from fds.analyticsapi.paengineapi.v1.configuration import Configuration as PaEngineConfiguration
from fds.analyticsapi.paengineapi.v1.api_client import ApiClient as PaEngineApiClient
from fds.analyticsapi.paengineapi.v1.api.components_api import ComponentsApi
from fds.analyticsapi.paengineapi.v1.models.component_entity import ComponentEntity

from fds.analyticsapi.pabatchapi.v1.configuration import Configuration as PaBatchConfiguration
from fds.analyticsapi.pabatchapi.v1.api_client import ApiClient as PaBatchApiClient
from fds.analyticsapi.pabatchapi.v1.api.batch_api import BatchApi
from fds.analyticsapi.pabatchapi.v1.models.calculation_parameters import CalculationParameters
from fds.analyticsapi.pabatchapi.v1.models.date_parameters import DateParameters


host = "https://api.factset.com"
username = "<username-serial>"
password = "<apiKey>"
verify_ssl = False

pa_batch_config = PaBatchConfiguration()
pa_batch_config.host = host
pa_batch_config.username = username
pa_batch_config.password = password
pa_batch_config.verify_ssl = False

pa_engine_config = PaEngineConfiguration()
pa_engine_config.host = host
pa_engine_config.username = username
pa_engine_config.password = password
pa_engine_config.verify_ssl = False

pa_batch_api_client = PaBatchApiClient(pa_batch_config)
pa_engine_api_client = PaEngineApiClient(pa_engine_config)

document_name="PA_DOCUMENTS:DEFAULT"
accounts = ["BENCH:SP50", "BENCH:R.1000"]
benchmarks = ["BENCH:R.2000"]
dates = DateParameters()
dates.startdate = "-2M"
dates.enddate = "0"
dates.frequency = "Monthly"

components_api = ComponentsApi(pa_engine_api_client)
component_api_get_result = components_api.get_all_with_http_info(document_name)
component_id = list(component_api_get_result[0].keys())[0]
print("Component ID: " + component_id)

calculation_parameters_list = [CalculationParameters(component_id, accounts, benchmarks, dates), CalculationParameters(component_id, accounts, benchmarks)]
batch_api = BatchApi(pa_batch_api_client)
batch_api_post_result =  batch_api.create_with_http_info(calculation_parameters_list=calculation_parameters_list)

if(batch_api_post_result[1] != 202):
    print(batch_api_post_result[2].get("x-datadirect-request-key"))
    quit()

status_location = batch_api_post_result[2].get("location")
splits = status_location.split("/")
batch_id = splits[-1]
print("Batch Id: " + batch_id)

batch_status = batch_api.get_status_by_id_with_http_info(batch_id)
while (batch_status[1] == 200 and (batch_status[0].status == "Queued" or batch_status[0].status == "Executing")):
    age_value = batch_status[2].get("cache-control")
    if(age_value != None):
        max_age = age_value.replace("max-age=", "")
        print('Sleeping: ' + max_age)
        time.sleep(int(max_age))
    batch_status = batch_api.get_status_by_id_with_http_info(batch_id)

if(batch_status[1] != 200):
    print(batch_status[2].get("x-datadirect-request-key"))
    quit()

for calculation_id, calculation_details in batch_status[0].calculations.items(): 
    if calculation_details.status == "Failed":
        print("CalculationId : " + calculation_id + " Failed!!!")
        print("Error message : " + calculation_details.error)

for calculation_id, calculation_details in batch_status[0].calculations.items(): 
    if calculation_details.status == "Success":
        batch_calculation_result = batch_api.get_by_url_with_http_info(calculation_details.result)
        
        if(batch_calculation_result[1] != 200):
            print(batch_calculation_result[2].get('x-datadirect-request-key'))
            quit()
        
        result =  json_format.Parse(json.dumps(batch_calculation_result[0]), Package())
        print(MessageToJson(result)) # To print the result object as a JSON
        #print(MessageToDict(result)) # To print the result object as a Dictionary

 

Building and running a batch
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;

using FactSet.AnalyticsAPI.PABatchAPI.v1.Api;
using FactSet.AnalyticsAPI.PABatchAPI.v1.Client;
using FactSet.AnalyticsAPI.PABatchAPI.v1.Model;
using FactSet.AnalyticsAPI.PAEngineAPI.v1.Api;
using FactSet.AnalyticsAPI.PAEngineAPI.v1.Model;
using FactSet.Protobuf.Stach;
using Google.Protobuf;

namespace FactSet.AnalyticsAPI.PABatchAPI.v1.Examples
{
    class Program
    {
        private static Configuration paBatchApiConfiguration;
        private static PAEngineAPI.v1.Client.Configuration paEngineApiConfiguration;
        private const string BASE_PATH = "https://api.factset.com";
        private const string USERNAME = "<username-serial>";
        private const string PASSWORD = "<apiKey>";

        private static Configuration GetPaBatchApiConfiguration()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (paBatchApiConfiguration != null)
            {
                return paBatchApiConfiguration;
            }

            paBatchApiConfiguration = new Configuration
            {
                BasePath = BASE_PATH,
                Username = USERNAME,
                Password = PASSWORD
            };

            return paBatchApiConfiguration;
        }

        private static PAEngineAPI.v1.Client.Configuration GetPaEngineApiConfiguration()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (paBatchApiConfiguration != null)
            {
                return paEngineApiConfiguration;
            }

            paEngineApiConfiguration = new PAEngineAPI.v1.Client.Configuration
            {
                BasePath = BASE_PATH,
                Username = USERNAME,
                Password = PASSWORD
            };

            return paEngineApiConfiguration;
        }

        static void Main(string[] args)
        {
            try
            {
                var componentsApi = new ComponentsApi(GetPaEngineApiConfiguration());

                // PA_DOCUMENTS:DEFAULT is default document available to all users.
                PAEngineAPI.v1.Client.ApiResponse<Dictionary<string, ComponentListEntity>> componentGetAllResponse =
                    componentsApi.GetAllWithHttpInfo("PA_DOCUMENTS:DEFAULT");

                if (componentGetAllResponse.StatusCode != 200)
                {
                    LogError(componentGetAllResponse);
                    return;
                }

                var componentId = componentGetAllResponse.Data.First().Key;

                var accounts = new List<string> { "BENCH:SP50", "BENCH:R.1000" };
                var benchmarks = new List<string> { "BENCH:R.1000" };
                var dates = new Model.DateParameters()
                {
                    Startdate = "-2M",
                    Enddate = "0",
                    Frequency = Model.DateParameters.FrequencyEnum.Monthly
                };

                var inputBody = new List<Model.CalculationParameters>
                {
                    new Model.CalculationParameters(componentId, accounts, benchmarks, dates),
                    new Model.CalculationParameters(componentId, accounts, benchmarks)
                };
                var batchApi = new BatchApi(GetPaBatchApiConfiguration());
                var createResponse = batchApi.CreateWithHttpInfo(inputBody);

                if (createResponse.StatusCode != 202)
                {
                    LogError(createResponse);
                    return;
                }

                // Parse the the Location header for calculation Id
                createResponse.Headers.TryGetValue("Location", out string location);
                if (string.IsNullOrWhiteSpace(location))
                {
                    LogError(createResponse);
                    return;
                }

                var calculationId = location.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries).Last();
                ApiResponse<BatchCalculationParameters> getStatus = null;

                while (getStatus == null || getStatus.Data.Status == BatchCalculationParameters.StatusEnum.Queued ||
                       getStatus.Data.Status == BatchCalculationParameters.StatusEnum.Executing)
                {
                    if (getStatus != null && getStatus.Headers.ContainsKey("Cache-Control"))
                    {
                        var ageValue = getStatus.Headers["Cache-Control"];
                        if (string.IsNullOrWhiteSpace(ageValue))
                        {
                            Console.WriteLine("Sleeping for 2 seconds");
                            // Sleep for atleast 2 seconds.
                            Thread.Sleep(2000);
                        }
                        else
                        {
                            int age = int.Parse(ageValue.Replace("max-age=", ""));
                            Console.WriteLine($"Sleeping for {age} seconds");
                            Thread.Sleep(age * 1000);
                        }
                    }

                    getStatus = batchApi.GetStatusByIdWithHttpInfo(calculationId);
                }

                Console.WriteLine("Batch Completed!!!");

                foreach (var calculationParameters in getStatus.Data.Calculations.Where(w =>
                        w.Value.Status == CalculationCalculationParameters.StatusEnum.Failed))
                {
                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Failed!!!");
                    Console.WriteLine("Error message : " + calculationParameters.Value.Error);
                }

                foreach (var calculationParameters in getStatus.Data.Calculations.Where(w =>
                    w.Value.Status == CalculationCalculationParameters.StatusEnum.Success))
                {
                    var resultResponse = batchApi.GetByUrlWithHttpInfo(calculationParameters.Value.Result);
                    if (resultResponse.StatusCode != 200)
                    {
                        LogError(resultResponse);
                        return;
                    }

                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Succeeded!!!");

                    JsonParser.Settings jpSettings = JsonParser.Settings.Default;
                    JsonParser jp = new JsonParser(jpSettings.WithIgnoreUnknownFields(true));
                    var package = jp.Parse<Package>(resultResponse.Data);

                    Console.WriteLine("CalculationId : " + calculationParameters.Key + " Result");
                    Console.WriteLine(package.ToString());
                }

                Console.ReadKey();
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error!!!");
                Console.WriteLine("Error Code: " + e.ErrorCode);
                Console.WriteLine(e.ErrorContent);
            }
        }

        private static void LogError<T>(ApiResponse<T> response)
        {
            Console.WriteLine("Error!!!");
            Console.WriteLine("Status Code: " + response.StatusCode);
            Console.WriteLine("Request Key: " + response.Headers["X-Factset-Api-Request-Key"]);
        }

        private static void LogError<T>(PAEngineAPI.v1.Client.ApiResponse<T> response)
        {
            Console.WriteLine("Error!!!");
            Console.WriteLine("Status Code: " + response.StatusCode);
            Console.WriteLine("Request Key: " + response.Headers["X-Factset-Api-Request-Key"]);
        }
    }
}

 

package examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;

import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.InvalidProtocolBufferException;
import com.factset.protobuf.stach.PackageProto.Package.Builder;
import com.factset.protobuf.stach.PackageProto.Package;

import factset.analyticsapi.pabatchapi.v1.ApiClient;
import factset.analyticsapi.pabatchapi.v1.ApiException;
import factset.analyticsapi.pabatchapi.v1.ApiResponse;
import factset.analyticsapi.pabatchapi.v1.api.BatchApi;
import factset.analyticsapi.paengineapi.v1.api.ComponentsApi;
import factset.analyticsapi.paengineapi.v1.models.ComponentListEntity;
import factset.analyticsapi.pabatchapi.v1.models.*;

public class Example {
	private static ApiClient apiPaBatchClient = null;
	private static factset.analyticsapi.paengineapi.v1.ApiClient apiPaEngineClient = null;
	private static final String BASE_PATH = "https://api.factset.com";
	private static final String USERNAME = "<username-serial>";
	private static final String PASSWORD = "<apiKey>";

	public static void main(String[] args) throws InterruptedException {
		try {
			ComponentsApi componentsApi = new ComponentsApi(apiPaEngineClientFactory());
			Map<String, ComponentListEntity> components = componentsApi.getAll("PA_DOCUMENTS:DEFAULT");
			String componentId = components.entrySet().stream().findFirst().get().getKey();
			System.out.println("ComponentID: " + componentId);

			CalculationParameters parameters = new CalculationParameters();
			parameters.componentid(componentId);
			parameters.setAccounts(Arrays.asList("BENCH:SP50", "BENCH:R.1000"));
			parameters.setBenchmarks(Arrays.asList("BENCH:R.1000"));
			
			DateParameters dates = new DateParameters();
			dates.setStartdate("-2M");
			dates.setEnddate("0");
			dates.setFrequency(DateParameters.FrequencyEnum.MONTHLY);
			parameters.dates(dates);

			List<CalculationParameters> parametersList = new ArrayList<CalculationParameters>();
			parametersList.add(parameters);
			parametersList.add(parameters);

			BatchApi batchApi = new BatchApi(apiPaBatchClientFactory());
			ApiResponse<Void> calculationResult = batchApi.createWithHttpInfo(parametersList);

			Map<String, List<String>> headers = calculationResult.getHeaders();
			String locationToPoll = headers.get("Location").get(0);
			String[] splits = locationToPoll.split("/");
			String requestId = splits[splits.length - 1];

			ApiResponse<BatchCalculationParameters> getStatus = null;

			while (getStatus == null 
					|| getStatus.getData().getStatus() == BatchCalculationParameters.StatusEnum.QUEUED 
					|| getStatus.getData().getStatus() == BatchCalculationParameters.StatusEnum.EXECUTING) {
      			if(getStatus != null) {
					List<String> cacheControl = getStatus.getHeaders().get("Cache-Control");
					if (cacheControl != null) {
						int maxAge = Integer.parseInt(cacheControl.get(0).replaceAll("max-age=", ""));
						System.out.println("Sleeping for: " + maxAge + " seconds");
						Thread.sleep(maxAge * 1000);
					} else {
						System.out.println("Sleeping for: 2 seconds");
						Thread.sleep(2 * 1000);
					}
				}
				getStatus = batchApi.getStatusByIdWithHttpInfo(requestId);
			}
      
			System.out.println("Batch Completed!!!");

			for (Map.Entry<String, CalculationCalculationParameters> calculationParameters : getStatus.getData().getCalculations().entrySet()) {
				if (calculationParameters.getValue().getStatus() == CalculationCalculationParameters.StatusEnum.FAILED) {
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Failed!!!");
					System.out.println("Error message : " + calculationParameters.getValue().getError());
				}
			}

			for (Map.Entry<String, CalculationCalculationParameters> calculationParameters : getStatus.getData().getCalculations().entrySet()) {
				if (calculationParameters.getValue().getStatus() == CalculationCalculationParameters.StatusEnum.SUCCESS) {
					ApiResponse<String> resultResponse = batchApi.getByUrlWithHttpInfo(calculationParameters.getValue().getResult());
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Succeeded!!!");
					System.out.println("CalculationId : " + calculationParameters.getKey() + " Result");
					
					Builder builder = Package.newBuilder();
					try {
						JsonFormat.parser().ignoringUnknownFields().merge(resultResponse.getData(), builder);
					} catch (InvalidProtocolBufferException e) {
						System.out.println("Error while deserializing the response");
						e.printStackTrace();
					}

					Package result = (Package) builder.build();
					System.out.println(result.toString()); // To print the result object as a JSON
				}
			}
		} catch (ApiException e) {
			System.err.println("ResponseBody: " + e.getResponseBody());
			System.err.println(
					"X-DataDirect-Request-Key: " + e.getResponseHeaders().get("X-DataDirect-Request-Key").get(0));
			e.printStackTrace();
		} catch (factset.analyticsapi.paengineapi.v1.ApiException e) {
			System.err.println("ResponseBody: " + e.getResponseBody());
			System.err.println(
					"X-DataDirect-Request-Key: " + e.getResponseHeaders().get("X-DataDirect-Request-Key").get(0));
			e.printStackTrace();
		}
	}

	private static ApiClient apiPaBatchClientFactory() {
		if (apiPaBatchClient != null) {
			return apiPaBatchClient;
		}

		apiPaBatchClient = new ApiClient();
		apiPaBatchClient.setBasePath(BASE_PATH);
		apiPaBatchClient.setUsername(USERNAME); // username-serial combination
		apiPaBatchClient.setPassword(PASSWORD); // api key

		apiPaBatchClient.setVerifyingSsl(false);

		return apiPaBatchClient;
	}

	private static factset.analyticsapi.paengineapi.v1.ApiClient apiPaEngineClientFactory() {
		if (apiPaEngineClient != null) {
			return apiPaEngineClient;
		}

		apiPaEngineClient = new factset.analyticsapi.paengineapi.v1.ApiClient();
		apiPaEngineClient.setBasePath(BASE_PATH);
		apiPaEngineClient.setUsername(USERNAME); // username-serial combination
		apiPaEngineClient.setPassword(PASSWORD); // api key

		apiPaEngineClient.setVerifyingSsl(false);

		return apiPaEngineClient;
	}
}

 

import time
import json

from google.protobuf.json_format import MessageToJson
from google.protobuf.json_format import MessageToDict

from fds.protobuf.stach.Package_pb2 import Package
from google.protobuf import json_format

from fds.analyticsapi.paengineapi.v1.configuration import Configuration as PaEngineConfiguration
from fds.analyticsapi.paengineapi.v1.api_client import ApiClient as PaEngineApiClient
from fds.analyticsapi.paengineapi.v1.api.components_api import ComponentsApi
from fds.analyticsapi.paengineapi.v1.models.component_entity import ComponentEntity

from fds.analyticsapi.pabatchapi.v1.configuration import Configuration as PaBatchConfiguration
from fds.analyticsapi.pabatchapi.v1.api_client import ApiClient as PaBatchApiClient
from fds.analyticsapi.pabatchapi.v1.api.batch_api import BatchApi
from fds.analyticsapi.pabatchapi.v1.models.calculation_parameters import CalculationParameters
from fds.analyticsapi.pabatchapi.v1.models.date_parameters import DateParameters


host = "https://api.factset.com"
username = "<username-serial>"
password = "<apiKey>"
verify_ssl = False

pa_batch_config = PaBatchConfiguration()
pa_batch_config.host = host
pa_batch_config.username = username
pa_batch_config.password = password
pa_batch_config.verify_ssl = False

pa_engine_config = PaEngineConfiguration()
pa_engine_config.host = host
pa_engine_config.username = username
pa_engine_config.password = password
pa_engine_config.verify_ssl = False

pa_batch_api_client = PaBatchApiClient(pa_batch_config)
pa_engine_api_client = PaEngineApiClient(pa_engine_config)

document_name="PA_DOCUMENTS:DEFAULT"
accounts = ["BENCH:SP50", "BENCH:R.1000"]
benchmarks = ["BENCH:R.2000"]
dates = DateParameters()
dates.startdate = "-2M"
dates.enddate = "0"
dates.frequency = "Monthly"

components_api = ComponentsApi(pa_engine_api_client)
component_api_get_result = components_api.get_all_with_http_info(document_name)
component_id = list(component_api_get_result[0].keys())[0]
print("Component ID: " + component_id)

calculation_parameters_list = [CalculationParameters(component_id, accounts, benchmarks, dates), CalculationParameters(component_id, accounts, benchmarks)]
batch_api = BatchApi(pa_batch_api_client)
batch_api_post_result =  batch_api.create_with_http_info(calculation_parameters_list=calculation_parameters_list)

if(batch_api_post_result[1] != 202):
    print(batch_api_post_result[2].get("x-datadirect-request-key"))
    quit()

status_location = batch_api_post_result[2].get("location")
splits = status_location.split("/")
batch_id = splits[-1]
print("Batch Id: " + batch_id)

batch_status = batch_api.get_status_by_id_with_http_info(batch_id)
while (batch_status[1] == 200 and (batch_status[0].status == "Queued" or batch_status[0].status == "Executing")):
    age_value = batch_status[2].get("cache-control")
    if(age_value != None):
        max_age = age_value.replace("max-age=", "")
        print('Sleeping: ' + max_age)
        time.sleep(int(max_age))
    batch_status = batch_api.get_status_by_id_with_http_info(batch_id)

if(batch_status[1] != 200):
    print(batch_status[2].get("x-datadirect-request-key"))
    quit()

for calculation_id, calculation_details in batch_status[0].calculations.items(): 
    if calculation_details.status == "Failed":
        print("CalculationId : " + calculation_id + " Failed!!!")
        print("Error message : " + calculation_details.error)

for calculation_id, calculation_details in batch_status[0].calculations.items(): 
    if calculation_details.status == "Success":
        batch_calculation_result = batch_api.get_by_url_with_http_info(calculation_details.result)
        
        if(batch_calculation_result[1] != 200):
            print(batch_calculation_result[2].get('x-datadirect-request-key'))
            quit()
        
        result =  json_format.Parse(json.dumps(batch_calculation_result[0]), Package())
        print(MessageToJson(result)) # To print the result object as a JSON
        #print(MessageToDict(result)) # To print the result object as a Dictionary

 

Change Logs

v1 (Released on 04/24/19)
Summary
  • v1.3.1 - Released on 08/01/19
  • v1.3.0 - Released on 07/04/19
  • v1.2.1 - Released on 06/13/19
  • v1.2.0 - Released on 04/24/19
  • v1.1.0 - Released on 03/27/19
  • v1.0.0 - Released on 03/01/19
Functionality Additions
  • Changed frequency calculation parameter to accept complete word instead of abbreviations [v1.2.0]
  • Added an endpoint to list all supported frequencies [v1.1.0]
  • Added support for multiple portfolios and benchmarks [v1.1.0]
  • Added ability to create, fetch, and delete batch calculations [v1.0.0]
  • Initial release [v1.0.0]
Changes
  • Added points count limit and rate limit headers [v1.3.0]
Bug Fixes
  • Fixed points count functionality while decrementing the counter to match what was done while incrementing the counter [v1.3.1]
  • Fixed date validations for certain frequency, start date and end date combinations [v1.2.1]