### Run PRB Job (Python SDK Example) Source: https://developer.factset.com/api-catalog/portfolio-reporting-batcher-api Example demonstrating how to start a Portfolio Reporting Batcher job using the Python SDK. ```APIDOC ```python import os import fds.sdk.PortfolioReportingBatcher from fds.sdk.PortfolioReportingBatcher.apis import RunsApi from fds.sdk.PortfolioReportingBatcher.models import * from fds.sdk.PortfolioReportingBatcher import ApiClient, Configuration, ApiException from fds.sdk.utils.authentication import ConfidentialClient from urllib3 import Retry host = os.environ['FACTSET_HOST'] + "/analytics/prb/v1/" fds_username = os.environ['FACTSET_USERNAME'] fds_api_key = os.environ['FACTSET_API_KEY'] def main(): # Supported authentication methods are below, # choose one that satisfies your use case. # Basic authentication: FactSetApiKey # See https://github.com/FactSet/enterprise-sdk#api-key # for information how to create an API key # region BasicAuthentication 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 = "" config.verify_ssl = False # endregion # (Preferred) OAuth 2.0: FactSetOAuth2 # See https://github.com/FactSet/enterprise-sdk#oauth-20 # for information on how to create the app-config.json file # See https://github.com/FactSet/enterprise-sdk-utils-python#authentication # for more information on using the ConfidentialClient class # Comment the above basic authentication scenario(region:BasicAuthentication) and Uncomment below lines for FactSetOAuth2 Authentication # region FactSetOAuth2 # config = Configuration( # fds_oauth_client=ConfidentialClient('/path/to/app-config.json') # ) # endregion # 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) runs_api = RunsApi(api_client) try: start_job = StartJob( job_name="PA3_API_QARC", job_type=JobTypes("PA") ) start_job_root = StartJobRoot(data=start_job) response_body, status_code, response_headers = runs_api.start_job_run_with_http_info(start_job_root=start_job_root) print("Response Body:", response_body) print("Status Code:", status_code) print("Response Headers:", response_headers) except ApiException as e: print("Api exception Encountered") print(e) exit() if __name__ == '__main__': main() ``` ``` -------------------------------- ### Get Liquidity Volume Analytics API Setup Source: https://developer.factset.com/api-catalog/best-execution-analytics-for-smarter-trading-beast-api Initializes the API client and configuration for accessing liquidity volume analytics. Supports OAuth 2.0 and Basic Authentication methods. ```python from os import getenv from fds.sdk.utils.authentication import ConfidentialClient import fds.sdk.BestExecutionAnalyticsforSmarterTradingBEAST from fds.sdk.BestExecutionAnalyticsforSmarterTradingBEAST.api import liquidity_Volume_analytics_api def getConfiguration(): # (Preferred) OAuth 2.0: FactSetOAuth2 # See https://github.com/FactSet/enterprise-sdk#oauth-20 # for information on how to create the app-config.json file # See https://github.com/FactSet/enterprise-sdk-utils-python#authentication # for more information on using the ConfidentialClient class configuration = fds.sdk.BestExecutionAnalyticsforSmarterTradingBEAST.Configuration( fds_oauth_client = ConfidentialClient('/path/to/app-config.json') ) # Uncomment the below lines for Basic Authentication # Basic authentication: FactSetApiKey # See https://github.com/FactSet/enterprise-sdk#api-key # for information how to create an API key # configuration = fds.sdk.FactSetTrading.Configuration( # host=getenv("FACTSET_HOST") + "/trading/ems/v0", # username=getenv("FACTSET_USERNAME"), # password=getenv("FACTSET_PASSWORD") # ) return configuration ``` -------------------------------- ### Chart Generation Service API - Getting Started Source: https://developer.factset.com/api-catalog/chart-generation-service This snippet demonstrates the initial steps for using the Chart Generation Services API in Python. It covers importing necessary packages and authenticating using a confidential client and configuration file. ```Python # Chart Generation Services API - Used to generate chart images, retrieve chart categories and their templates. # # The following code snippets demonstrate how to use the CGS API endpoints by guiding you through the following steps: # 1. Import Python packages # 2. Authenticate using ConfidentialClient & config file # 2.1 Create application - https://developer.factset.com/learn/authentication-oauth2 # 2.2 Download config file when prompted and move it to your development environment ``` -------------------------------- ### Python SDK Example Source: https://developer.factset.com/api-catalog/fixed-income-calculation-api Demonstrates how to use the Python SDK to configure authentication, set up API client, and prepare security data for fixed income calculations. ```APIDOC ## Python SDK Example ### Description This code snippet shows how to initialize the Fixed Income Calculation API client using Python, including authentication setup (Basic or OAuth2) and defining security parameters for calculations. ### Method N/A (SDK Usage) ### Endpoint N/A (SDK Usage) ### Parameters N/A (SDK Usage) ### Request Example ```python import sys import time import uuid import os import pandas as pd from fds.sdk.FixedIncomeCalculation import Configuration, ApiClient from fds.sdk.FixedIncomeCalculation.api.fi_calculations_api import FICalculationsApi from fds.sdk.FixedIncomeCalculation.model.fi_market_environment import FIMarketEnvironment from fds.sdk.FixedIncomeCalculation.model.fi_security import FISecurity from fds.sdk.FixedIncomeCalculation.model.fi_job_settings import FIJobSettings from fds.sdk.FixedIncomeCalculation.model.fi_calculation_parameters import FICalculationParameters from fds.sdk.FixedIncomeCalculation.model.fi_calculation_parameters_root import FICalculationParametersRoot from fds.sdk.FixedIncomeCalculation.model.fi_bank_loans import FIBankLoans from fds.sdk.FixedIncomeCalculation.model.fi_municipal_bonds import FIMunicipalBonds from fds.sdk.FixedIncomeCalculation.model.fi_municipal_bonds_for_job_settings import FIMunicipalBondsForJobSettings from fds.protobuf.stach.extensions.StachVersion import StachVersion from fds.protobuf.stach.extensions.StachExtensionFactory import StachExtensionFactory from fds.sdk.utils.authentication import ConfidentialClient from urllib3 import Retry host = os.environ['FACTSET_HOST'] fds_username = os.environ['FACTSET_USERNAME'] fds_api_key = os.environ['FACTSET_API_KEY'] def main(): # Supported authentication methods are below, # choose one that satisfies your use case. # Basic authentication: FactSetApiKey # See https://github.com/FactSet/enterprise-sdk#api-key # for information how to create an API key # region BasicAuthentication 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 = "" config.verify_ssl = False # endregion # (Preferred) OAuth 2.0: FactSetOAuth2 # See https://github.com/FactSet/enterprise-sdk#oauth-20 # for information on how to create the app-config.json file # See https://github.com/FactSet/enterprise-sdk-utils-python#authentication # for more information on using the ConfidentialClient class # Comment the above basic authentication scenario(region:BasicAuthentication) and Uncomment below lines for FactSetOAuth2 Authentication # region FactSetOAuth2 # config = Configuration( # fds_oauth_client=ConfidentialClient('/path/to/app-config.json') # ) # endregion # 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" ] fi_bank_loans_for_securities = FIBankLoans( ignore_sinking_fund=True ) fi_municipal_bonds_for_securities = FIMunicipalBonds( ignore_sinking_fund=True ) security1 = FISecurity( calc_from_method="Price", calc_from_value=100.285, face=10000.0, symbol="912828ZG8", settlement="20201202", discount_curve="UST", bank_loans=fi_bank_loans_for_securities, municipal_bonds=fi_municipal_bonds_for_securities ) security2 = FISecurity( # ... other security details ) # Example of how to use the API (actual call would depend on specific method) # fi_calculations_api = FICalculationsApi(api_client) # result = fi_calculations_api.post_limited_complex_analytics(...) if __name__ == "__main__": main() ``` ``` -------------------------------- ### Get Liquidity Quotes Analytics using BEAST API Source: https://developer.factset.com/api-catalog/best-execution-analytics-for-smarter-trading-beast-api Configuration setup for accessing the Liquidity Quotes Analytics API. This example shows how to configure authentication, with OAuth 2.0 as the preferred method. ```python from os import getenv from fds.sdk.utils.authentication import ConfidentialClient import fds.sdk.BestExecutionAnalyticsforSmarterTradingBEAST from fds.sdk.BestExecutionAnalyticsforSmarterTradingBEAST.api import liquidity_Quotes_analytics_api def getConfiguration(): # (Preferred) OAuth 2.0: FactSetOAuth2 # See https://github.com/FactSet/enterprise-sdk#oauth-20 # for information on how to create the app-config.json file # See https://github.com/FactSet/enterprise-sdk-utils-python#authentication # for more information on using the ConfidentialClient class configuration = fds.sdk.BestExecutionAnalyticsforSmarterTradingBEAST.Configuration( fds_oauth_client = ConfidentialClient('/path/to/app-config.json') ) # Uncomment the below lines for Basic Authentication # Basic authentication: FactSetApiKey # See https://github.com/FactSet/enterprise-sdk#api-key # for information how to create an API key # configuration = fds.sdk.FactSetTrading.Configuration( # host=getenv("FACTSET_HOST") + "/trading/ems/v0", # username=getenv("FACTSET_USERNAME"), # password=getenv("FACTSET_PASSWORD") # ) return configuration ``` -------------------------------- ### Java HTTP GET Example Source: https://developer.factset.com/api-catalog/factset-intraday-tick-history-api Example code demonstrating how to make an HTTP GET request to the FactSet Intraday Tick History API using Java, including handling deflate and gzip compression and XML parsing. ```Java import java.io.*; import java.util.zip.*; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.xml.parsers.*; import org.xml.sax.*; public class MyXmlParser implements ContentHandler { public static void main(String[] args) { try { // setup the request URL url = new URL( "https://datadirect-beta.factset.com/services/TickHistory?" + "id=FDS-USA&format=xml" + "&date=20170914&fields=LAST_1,LAST_TIME_1,LAST_VOL_1" + "&interval=1H&st=100000&et=130000" ); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Accept-Encoding", "deflate, gzip"); conn.setRequestProperty("Authorization", "Basic AaBbCcDdEeFfGgHhIi1234=="); // getInputStream will implicitly connect and get the response InputStream inputStream = conn.getInputStream(); // uncompress the response if (conn.getContentEncoding().equals("deflate")) inputStream = new InflaterInputStream(inputStream, new Inflater(true)); else if (conn.getContentEncoding().equals("gzip")) inputStream = new GZIPInputStream(inputStream); XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); reader.setContentHandler(new MyXMLParser()); reader.parse(new InputSource(inputStream)); } catch (IOException e) { // Deal with IOException } catch (SAXException e) { // Deal with SAXException } catch (ParserConfigurationException e) { // Deal with ParserConfigurationException } } public void startElement(String uri, String localname, String qName, Attributes atts) { if (qName.equals("Error")) System.out.println("Error code: " + atts.getValue("code") + ", description: " + atts.getValue("description")); else if (qName.equals("Records")) { currentReqSym = atts.getValue("req_sym"); currentKey = atts.getValue("key"); currentStale = atts.getValue("stale"); } else if (qName.equals("Field")) System.out.println("req_sym: " + currentReqSym + ", key: " + currentKey + ", stale: " + currentStale + ", id: " + atts.getValue("id") + ", name: " + atts.getValue("name") + " = " + atts.getValue("value")); } private String currentReqSym, currentKey, currentStale; public void characters(char [] ch, int start, int length) {} public void endDocument() {} public void endElement(String uri, String localname, String qName) {} public void endPrefixMapping(String prefix) {} public void ignorableWhitespace(char [] ch, int start, int length) {} public void processingInstruction(String target, String data) {} public void setDocumentLocator(Locator locator) {} public void skippedEntity(String name) {} public void startDocument() {} public void startPrefixMapping(String prefix, String uri) {} } // class MyXMLParser ``` -------------------------------- ### Build PA Calculation Parameters List Source: https://developer.factset.com/api-catalog/pa-engine-api This example demonstrates how to build a list of PA Calculation Parameters. It includes setting up component IDs, accounts, benchmarks, and date parameters for calculations. Use this to configure specific calculation requests. ```java import javax.ws.rs.client.ClientBuilder; import java.io.File; import java.io.FileOutputStream; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import java.util.UUID; public class PAEngineMultipleUnitExample { private static FdsApiClient apiClient = null; private static String BASE_PATH = System.getenv("FACTSET_HOST"); private static String USERNAME = System.getenv("FACTSET_USERNAME"); private static String PASSWORD = System.getenv("FACTSET_PASSWORD"); private static String PA_DEFAULT_DOCUMENT = "pa3_documents:/pa_api_default_document-rbics"; private static String COMPONENT_NAME = "Multiple Portfolios"; private static String COMPONENT_CATEGORY = "Exposures & Characteristics / Exposures & Characteristics"; private static String COLUMN_NAME = "Port. Ending Weight"; private static String COLUMN_CATEGORY = "Portfolio/Position Data"; private static String COULMN_DIRECTORY = "Factset"; private static String GROUP_NAME = "Class - Bloomberg Muni"; private static String GROUP_CATEGORY = "Fixed Income/Municipals/Class"; private static String GROUP_DIRECTORY = "Factset"; private static String PRICING_SOURCE_NAME = "MSCI - Gross"; private static String PRICING_SOURCE_CATEGORY = "MSCI"; private static String PRICING_SOURCE_DIRECTORY = "Equity"; public static void main(String[] args) throws InterruptedException, JsonProcessingException { try { // Build PA Calculation Parameters List // Get all component from PA_DEFAULT_DOCUMENT with Name COMPONENT_NAME & category COMPONENT_CATEGORY ComponentsApi componentsApi = new ComponentsApi(getApiClient()); Map components = componentsApi.getPAComponents(PA_DEFAULT_DOCUMENT).getData(); String componentId = components.entrySet().stream() .filter(c -> c.getValue().getName().equals(COMPONENT_NAME) && c.getValue().getCategory().equals(COMPONENT_CATEGORY)) .iterator().next().getKey(); System.out.println( "ID of component with Name '" + COMPONENT_NAME + "' and category '" + COMPONENT_CATEGORY + "' : " + componentId); PACalculationParametersRoot calcParameters = new PACalculationParametersRoot(); PACalculationParameters paItem1 = new PACalculationParameters(); PACalculationParameters paItem2 = new PACalculationParameters(); paItem1.setComponentid(componentId); paItem2.setComponentid(componentId); PAIdentifier accountPaIdentifier1 = new PAIdentifier(); accountPaIdentifier1.setId("LION:100D-GB"); accountPaIdentifier1.setHoldingsmode("B&H"); // It can be B&H, TBR, OMS or EXT paItem1.addAccountsItem(accountPaIdentifier1); paItem2.addAccountsItem(accountPaIdentifier1); PAIdentifier accountPaIdentifier2 = new PAIdentifier(); accountPaIdentifier2.setId("LION:FXI-US"); accountPaIdentifier2.setHoldingsmode("B&H"); paItem1.addAccountsItem(accountPaIdentifier2); paItem2.addAccountsItem(accountPaIdentifier2); PAIdentifier benchmarkPaIdentifier = new PAIdentifier(); benchmarkPaIdentifier.setId("LION:OEF-US"); benchmarkPaIdentifier.setHoldingsmode("B&H"); paItem1.addBenchmarksItem(benchmarkPaIdentifier); paItem2.addBenchmarksItem(benchmarkPaIdentifier); PADateParameters dateParameters1 = new PADateParameters(); dateParameters1.setStartdate(""); dateParameters1.setEnddate("20240508"); dateParameters1.setFrequency("Single"); paItem1.setDates(dateParameters1); PADateParameters dateParameters2 = new PADateParameters(); dateParameters2.setStartdate("20240507"); dateParameters2.setEnddate("20240508"); dateParameters2.setFrequency("Daily"); paItem2.setDates(dateParameters2); // To add column overrides //PACalculationColumn column = new PACalculationColumn(); //column.setId(getColumnId(COLUMN_NAME, COLUMN_CATEGORY, COULMN_DIRECTORY)); //paItem1.addColumnsItem(column); //paItem2.addColumnsItem(column); // To add group overrides //PACalculationGroup group = new PACalculationGroup(); //group.setId(getGroupId(GROUP_NAME, GROUP_CATEGORY, GROUP_DIRECTORY)); //paItem1.addGroupsItem(group); //paItem2.addGroupsItem(group); // To add currency override //paItem1.currencyisocode("USD"); //paItem2.currencyisocode("USD"); // To add component detail. //paItem1.setComponentdetail("GROUPS"); // It can be GROUPS or TOTALS ``` -------------------------------- ### Run Sample Queries Source: https://developer.factset.com/api-catalog/conversational-api-powered-by-factset-mercury Demonstrates how to use the ConversationalAPIInterface to ask questions, including follow-up questions within a chat session, and generate charts. ```javascript export async function runSample() { const conversationalAPI = new ConversationalAPIInterface(); conversationalAPI.login(); conversationalAPI.setPollingParams(1000); // Ask a question to the Conversational API const {chatId, data: firstMessageData} = await conversationalAPI.askFactSetConversationalAPI( `What is Pepsi's enterprise value?` ); console.log('Conversational API response: ', firstMessageData); // Ask a follow-up question question to the Conversational API const {data: secondMessageData} = await conversationalAPI.askFactSetConversationalAPI( `What is their stock price?`, chatId ); console.log('Conversational API response: ', secondMessageData); // Ask a question to the Conversational API to generate a chart // Please note that the Chart Creator functionality is included in the Conversational API Plus with Chart Creator product. If you want to try this functionality, please contact your FactSet representative for more information. const {responseId, data: chartMessageData} = await conversationalAPI.askFactSetConversationalAPI( `Generate a price chart for tesla` ); console.log('Conversational API response: ', chartMessageData); // Check for downloadable files in the response and download // Please note that there may be multiple downloadable files in the response. This code snippet demonstrates downloading the first file. chartMessageData?.forEach(async (messageItem) => { if (messageItem.type === 'NextStep') { const fileItem = messageItem.value.find((nextStep) => nextStep.action === 'Download'); if (fileItem) { // Retrieve the chart file const fileBuffer = await conversationalAPI.downloadFile(fileItem.fileId, fileItem.fileName); /* If consuming in a browser, you can generate a download link for the file using the following code */ if (fileBuffer) { ``` -------------------------------- ### Python SDK Authentication and Setup Source: https://developer.factset.com/api-catalog/fixed-income-calculation-api Demonstrates how to set up authentication using either Basic Authentication (API Key) or OAuth 2.0 for the Fixed Income Calculation API client. Includes configuration for retries on specific HTTP status codes. ```python import sys import time import uuid import os import pandas as pd from fds.sdk.FixedIncomeCalculation import Configuration, ApiClient from fds.sdk.FixedIncomeCalculation.api.fi_calculations_api import FICalculationsApi from fds.sdk.FixedIncomeCalculation.model.fi_market_environment import FIMarketEnvironment from fds.sdk.FixedIncomeCalculation.model.fi_security import FISecurity from fds.sdk.FixedIncomeCalculation.model.fi_job_settings import FIJobSettings from fds.sdk.FixedIncomeCalculation.model.fi_calculation_parameters import FICalculationParameters from fds.sdk.FixedIncomeCalculation.model.fi_calculation_parameters_root import FICalculationParametersRoot from fds.sdk.FixedIncomeCalculation.model.fi_bank_loans import FIBankLoans from fds.sdk.FixedIncomeCalculation.model.fi_municipal_bonds import FIMunicipalBonds from fds.sdk.FixedIncomeCalculation.model.fi_municipal_bonds_for_job_settings import FIMunicipalBondsForJobSettings from fds.protobuf.stach.extensions.StachVersion import StachVersion from fds.protobuf.stach.extensions.StachExtensionFactory import StachExtensionFactory from fds.sdk.utils.authentication import ConfidentialClient from urllib3 import Retry host = os.environ['FACTSET_HOST'] fds_username = os.environ['FACTSET_USERNAME'] fds_api_key = os.environ['FACTSET_API_KEY'] def main(): # Supported authentication methods are below, # choose one that satisfies your use case. # Basic authentication: FactSetApiKey # See https://github.com/FactSet/enterprise-sdk#api-key # for information how to create an API key # region BasicAuthentication 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 = "" config.verify_ssl = False # endregion # (Preferred) OAuth 2.0: FactSetOAuth2 # See https://github.com/FactSet/enterprise-sdk#oauth-20 # for information on how to create the app-config.json file # See https://github.com/FactSet/enterprise-sdk-utils-python#authentication # for more information on using the ConfidentialClient class # Comment the above basic authentication scenario(region:BasicAuthentication) and Uncomment below lines for FactSetOAuth2 Authentication # region FactSetOAuth2 # config = Configuration( # fds_oauth_client=ConfidentialClient('/path/to/app-config.json') # ) # endregion # 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"] fi_bank_loans_for_securities = FIBankLoans( ignore_sinking_fund=True ) fi_municipal_bonds_for_securities = FIMunicipalBonds( ignore_sinking_fund=True ) security1 = FISecurity( calc_from_method="Price", calc_from_value=100.285, face=10000.0, symbol="912828ZG8", settlement="20201202", discount_curve="UST", bank_loans=fi_bank_loans_for_securities, municipal_bonds=fi_municipal_bonds_for_securities ) security2 = FISecurity( ``` -------------------------------- ### GET Snapshot Request Example Source: https://developer.factset.com/api-catalog/exchange-datafeed-snapshot-api-symbol-list This code snippet demonstrates how to issue a GET request to the Snapshot API to retrieve exchange data for a list of symbols and specified fields. It includes handling for compressed responses and parsing XML data. ```APIDOC ## GET /dfsnapshot ### Description Request a snapshot of exchange data for a list of symbols. ### Method GET ### Endpoint /dfsnapshot ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated list of symbols. - **fields** (string) - Required - Comma-separated list of fields to retrieve (e.g., ASK, BID, LAST). ### Request Example ``` https://api.factset.com/dfsnapshot/v1?ids=FDS-USA,IBM-USA,TWX-USA&fields=ASK,BID,LAST ``` ### Response #### Success Response (200) - The response will be in XML format by default, containing the requested exchange data. #### Response Example ```xml ``` ### Error Handling - The API returns an "Error" element in the XML response if an issue occurs. ``` -------------------------------- ### Get Categories Metadata Source: https://developer.factset.com/api-catalog/investment-research-api This example demonstrates how to retrieve a list of available categories using the Meta API. This endpoint requires no parameters. ```python with fds.sdk.InvestmentResearch.ApiClient(configuration) as api_client: api_instance = meta_api.MetaApi(api_client) try: api_response = api_instance.get_categories() pprint(api_response) except fds.sdk.InvestmentResearch.ApiException as e: print("Exception when calling MetaApi->get_categories: %s\n" % e) time.sleep(1) ``` -------------------------------- ### Get Returns Snapshot Source: https://developer.factset.com/api-catalog/factset-prices-api Retrieves returns as of a given date for predefined periods. This example demonstrates how to use the Python SDK to fetch this data. ```APIDOC ## Get Returns Snapshot ### Description Retrieves returns as of a given date for predefined periods, such as 1YR, 3YR, Since IPO, etc. ### Method GET ### Endpoint /factset-prices/v1/returns-snapshot ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated list of FactSet Security identifiers. - **date** (string) - Required - The date as of which to retrieve returns in YYYY-MM-DD format. - **periods** (string) - Required - Comma-separated list of predefined periods. Supported values: '1D', '5D', '1M', '3M', '6M', 'YTD', '1Y', '2Y', '3Y', '5Y', '10Y', 'SINCE_IPO'. - **currency** (string) - Optional - The currency of the returns to be returned. Defaults to USD. - **dividendAdjustSnapshot** (string) - Optional - Whether to adjust returns for dividends. Supported values: 'TRUE', 'FALSE'. Defaults to 'FALSE'. ### Request Example ``` GET https://api.factset.com/prices/v1/returns-snapshot?ids=FDS:12345&date=2023-12-31&periods=1Y,3Y,5Y÷ndAdjustSnapshot=TRUE ``` ### Response #### Success Response (200) - **data** (array) - An array of return snapshot objects. - **period** (string) - The return period. - **return** (number) - The security return for the specified period. - **currency** (string) - The currency of the returns. #### Response Example ```json { "data": [ { "period": "1Y", "return": 0.15, "currency": "USD" }, { "period": "3Y", "return": 0.10, "currency": "USD" } ] } ``` ``` -------------------------------- ### Configure and Calculate Risk Statistics Source: https://developer.factset.com/api-catalog/openrisk-api Instantiate the API client and configure the desired risk statistics for calculation. This example demonstrates setting up various statistics like ActiveFactorRisk and RawAssetCovarianceMatrix. ```python Stat( name="ActiveFactorRisk", level=StatCalculationLevel("Portfolio"), ), Stat( name="PercentActiveFactorVarianceToVariance", level=StatCalculationLevel("Portfolio"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="ActiveStockSpecificVarianceToStockSpecificRisk", level=StatCalculationLevel("Portfolio"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="PercentActiveFactorVarianceToVariance", level=StatCalculationLevel("Security"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="PercentActiveStockSpecificVarianceToVariance", level=StatCalculationLevel("Portfolio"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="PercentActiveStockSpecificVarianceToVariance", level=StatCalculationLevel("Security"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="PercentActiveVariance", level=StatCalculationLevel("Security"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="PortfolioBetaToBenchmark", level=StatCalculationLevel("Portfolio"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="PercentActiveFactorVarianceToVariance", level=StatCalculationLevel("Factor"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="ActiveFactorVarianceToRisk", level=StatCalculationLevel("FactorGroup"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="ActiveFactorEffect", level=StatCalculationLevel("Portfolio"), ), Stat( name="ActiveFactorEffect", level=StatCalculationLevel("Factor"), ), Stat( name="ActiveFactorEffect", level=StatCalculationLevel("Security"), ), Stat( name="ActiveFactorEffect", level=StatCalculationLevel("FactorSecurity"), ), Stat( name="ActiveExposure", level=StatCalculationLevel("FactorGroup"), ), Stat( name="RawFactorExposure", level=StatCalculationLevel("FactorSecurity"), ), Stat( name="RawFactorCovarianceMatrix", level=StatCalculationLevel("FactorFactor"), ), Stat( name="RawFactorCorrelationMatrix", level=StatCalculationLevel("FactorFactor"), ), Stat( name="RawAssetCovarianceMatrix", level=StatCalculationLevel("SecuritySecurity"), settings=StatCalculationSettings( correlated_specific_risk=True) ), Stat( name="RemoveCurrencyRiskFlag", level=StatCalculationLevel("Security"), ), Stat( name="ForcedRisklessFlag", level=StatCalculationLevel("Security"), ), ]), ), ) # CalculateFromHoldingsRequestBody try: # Calculate risk statistics # Since Factor Grouping doesn't use all the factors of the risk model, it's expected to see a warning for missing factors # example passing only required values which don't have defaults set pass except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### Get StreetAccount News for a Topic Source: https://developer.factset.com/api-catalog/real-time-news-api This example shows how to retrieve StreetAccount news for a specific topic, such as 'corona', using the `/news/article/searchByText` endpoint with a POST body. ```APIDOC ## POST /news/article/searchByText (Topic: 'corona') ### Description Retrieves StreetAccount news articles related to a specific topic. ### Method POST ### Endpoint /news/article/searchByText ### Parameters #### Request Body - **data** (object) - Required - The main object containing search parameters. - **text** (object) - Required - Parameters for text-based search. - **criteria** (object) - Required - Criteria for text search. - **selectionType** (string) - Required - Type of selection (e.g., 'include'). - **phrases** (array) - Required - Array of phrases to search for (e.g., ["corona"]) - **scope** (string) - Required - Scope of the search (e.g., 'all'). ### Request Example ```json { "data": { "text": { "criteria": { "selectionType": "include", "phrases": [ "corona" ], "scope": "all" } } } } ``` ### Response #### Success Response (200) - **data** (object) - Contains the search results for the specified topic. #### Response Example (Response structure depends on the actual API response, not provided in source) ``` -------------------------------- ### Basic Authentication Setup Source: https://developer.factset.com/api-catalog/factset-trading-api Configures the API client for Basic Authentication using API key credentials. Requires environment variables for host, username, and password. ```java ApiClient defaultClient = new ApiClient(); defaultClient.setBasePath(System.getenv("FACTSET_HOST") + "/trading/ems/v0"); defaultClient.setUsername(System.getenv("FACTSET_USERNAME")); defaultClient.setPassword(System.getenv("FACTSET_PASSWORD")); ``` -------------------------------- ### Python SDK - Initialize and Print Headlines Response Source: https://developer.factset.com/api-catalog/factset-news-api Demonstrates basic authentication using a configuration file and initializing the headlines API client. This snippet is useful for setting up the SDK and making an initial call to the /headlines endpoint. ```python from fds.sdk.utils.authentication import ConfidentialClient # please use pip install fds.sdk.utils import fds.sdk.FactSetNews from fds.sdk.FactSetNews.api import headlines_api # please use pip install fds.sdk.FactSetNews==1.0.0 from fds.sdk.FactSetNews.models import * from dateutil.parser import parse as dateutil_parser from pprint import pprint # Basic authentication: OAuth configuration = fds.sdk.FactSetNews.Configuration( fds_oauth_client=ConfidentialClient(r"") ) print("/headlines response: ") ``` -------------------------------- ### Get Time Zones Metadata Source: https://developer.factset.com/api-catalog/investment-research-api This example shows how to retrieve a list of available time zones using the Meta API. This endpoint requires no parameters. ```python with fds.sdk.InvestmentResearch.ApiClient(configuration) as api_client: api_instance = meta_api.MetaApi(api_client) try: api_response = api_instance.get_timezones() pprint(api_response) except fds.sdk.InvestmentResearch.ApiException as e: print("Exception when calling MetaApi->get_timezones: %s\n" % e) time.sleep(1) ``` -------------------------------- ### Get Cross-Sectional Data using Formula API Source: https://developer.factset.com/api-catalog/formula-api-time-series Demonstrates how to retrieve cross-sectional data by defining a universe and formulas. Requires authentication and SDK setup. ```python with fds.sdk.Formula.ApiClient(configuration) as api_client: # Create Instance api_instance = CrossSectionalApi(api_client) # Request Object to Define Parameters cross_sectional_request = CrossSectionalRequest( data=CrossSectionalRequestData( universe = "((FREF_MARKET_VALUE_COMPANY(0,USD,1))>5000 AND FG_EPS_CHG_FY1_ACT>P_PRICE_RETURNS(0,0,0) AND P_PRICE_RETURNS(0,NOW,0/0/-1)>VALUEX(\"SP50\",P_PRICE_RETURNS(0,NOW,0/0/-1)))==1", formulas = [ "PROPER_NAME", "P_PRICE_RETURNS(0,NOW,0/0/-1)" ], fsymId = "Y", flatten = "Y" ), ) # Send Request cross_sectional_response_wrapper = api_instance.get_cross_sectional_data_for_list(cross_sectional_request) cross_sectional_response = cross_sectional_response_wrapper.get_response_200() # Convert to Pandas Dataframe cross_sectional_results = pd.DataFrame(cross_sectional_response.to_dict()['data']) print(cross_sectional_results) ``` -------------------------------- ### Create and Download File in Browser Source: https://developer.factset.com/api-catalog/conversational-api-powered-by-factset-mercury Demonstrates how to create a file from a buffer and generate a download link for browser-based downloads. This is useful for client-side file handling. ```javascript const file = new Blob(fileBuffer, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); // Use the file directly or generate a download link (below) to download the file from the browser const downloadLink = URL.createObjectURL(file); ``` -------------------------------- ### Build and Run Single SPAR Calculation (Python) Source: https://developer.factset.com/api-catalog/style-performance-and-risk-analysis-spar-engine-api Demonstrates how to set up authentication, configure the API client, and initiate a single SPAR calculation using the Python SDK. Includes options for basic and OAuth2 authentication, and retry configurations. ```Python import time import pandas as pd import os import uuid from fds.sdk.SPAREngine.apis import SPARCalculationsApi from fds.sdk.SPAREngine.api.components_api import ComponentsApi from fds.sdk.SPAREngine import ApiClient, Configuration, ApiException from fds.sdk.SPAREngine.models import * from fds.sdk.utils.authentication import ConfidentialClient from fds.protobuf.stach.extensions.StachVersion import StachVersion from fds.protobuf.stach.extensions.StachExtensionFactory import StachExtensionFactory from urllib3 import Retry host = os.environ['FACTSET_HOST'] fds_username = os.environ['FACTSET_USERNAME'] fds_api_key = os.environ['FACTSET_API_KEY'] def main(): # Supported authentication methods are below, # choose one that satisfies your use case. # Basic authentication: FactSetApiKey # See https://github.com/FactSet/enterprise-sdk#api-key # for information how to create an API key # region BasicAuthentication 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 = "" config.verify_ssl = False # endregion # (Preferred) OAuth 2.0: FactSetOAuth2 # See https://github.com/FactSet/enterprise-sdk#oauth-20 # for information on how to create the app-config.json file # See https://github.com/FactSet/enterprise-sdk-utils-python#authentication # for more information on using the ConfidentialClient class # Comment the above basic authentication scenario(region:BasicAuthentication) and Uncomment below lines for FactSetOAuth2 Authentication # region FactSetOAuth2 # config = Configuration( # fds_oauth_client=ConfidentialClient('/path/to/app-config.json') # ) # endregion # 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_with_http_info(spar_document_name) component_id = [id for id in list( ``` -------------------------------- ### Python: Retrieve Entity Matches Source: https://developer.factset.com/api-catalog/factset-concordance-api Sample code to retrieve entity matches using the Concordance API. Requires authentication setup and SDK installation. ```Python from fds.sdk.utils.authentication import ConfidentialClient import fds.sdk.FactSetConcordance # To install, please use "pip install fds.sdk.utils fds.sdk.FactSetConcordance==0.24.2" from fds.sdk.FactSetConcordance.api import entity_match_api from fds.sdk.FactSetConcordance.models import * from dateutil.parser import parse as dateutil_parser from pprint import pprint # Authentication using OAuth configuration = fds.sdk.FactSetConcordance.Configuration( fds_oauth_client=ConfidentialClient('') # Path to config file from OAuth registration ) ``` -------------------------------- ### Get StreetAccount News for a Given Topic Source: https://developer.factset.com/api-catalog/real-time-news-api This example shows how to use the '/news/article/searchByText' endpoint with a POST body to retrieve news related to a specific topic, such as 'corona'. ```json /news/article/searchByText with POST body: { "data": { "text": { "criteria": { "selectionType": "include", ``` -------------------------------- ### Initialize Portfolio API Client with OAuth2 Source: https://developer.factset.com/api-catalog/portfolio-api Sets up the Portfolio API client using OAuth 2.0 authentication with a confidential client configuration. Requires a path to the application configuration file. ```python import os from fds.sdk.Portfolio import Configuration, ApiClient, ApiException from fds.sdk.Portfolio.api.model_accounts_api import ModelAccountsApi from fds.sdk.utils.authentication import ConfidentialClient host = os.getenv("FACTSET_HOST", "https://api.factset.com") + "/analytics/accounts/v3" username = os.getenv("FACTSET_USERNAME") password = os.getenv("FACTSET_PASSWORD") def main(): # Uncomment the below lines for Basic Authentication # region Basic authentication: FactSetApiKey # config = Configuration(host=host, username=username, password=password) # endregion # region (Preferred) OAuth 2.0: FactSetOAuth2 config = Configuration( fds_oauth_client=ConfidentialClient('/path/to/app-config.json'), host=host ) # endregion portfolio_api = ModelAccountsApi(api_client=ApiClient(configuration=config)) ``` -------------------------------- ### Get Security References Source: https://developer.factset.com/api-catalog/factset-prices-api Retrieves security name, date of first/last trade, security type, and more. This example demonstrates how to use the Python SDK to fetch this data. ```APIDOC ## Get Security References ### Description Fetches security name, date of first/last trade, security type, and more. ### Method GET ### Endpoint /factset-prices/v1/references ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated list of FactSet Security identifiers. ### Request Example ``` GET https://api.factset.com/prices/v1/references?ids=FDS:12345,FDS:67890 ``` ### Response #### Success Response (200) - **data** (array) - An array of reference objects. - **fsymId** (string) - The FactSet Security Identifier. - **name** (string) - The name of the security. - **firstTradeDate** (string) - The date of the first trade. - **lastTradeDate** (string) - The date of the last trade. - **securityType** (string) - The type of the security. #### Response Example ```json { "data": [ { "fsymId": "FDS:12345", "name": "Example Corp", "firstTradeDate": "2000-01-01", "lastTradeDate": "2024-01-15", "securityType": "Common Stock" } ] } ``` ```