Skip to main content

FactSet Quant Factor Library client library for Python

Project description

FactSet

FactSet Quant Factor Library client library for Python

API Version PyPi Apache-2 license

The FactSet FactSet Quant Factor Library (QFL) API helps to detect investment themes across global equity markets, incorporate ideas into your portfolio construction process, and transform raw data into actionable intelligence. Over 2000+ items spanning Factor Groups in-

  • Classification and Reference Data - Asset Data, Country, Industry, and Size
  • Market - Liquidity, Market Sensitivity, Momentum, Technical, Volatility
  • Core Fundamentals - Efficiency, Growth, Management, Profitability, Quality, Solvency, Value
  • Macro and Cross Asset - Commodity, FX Sensitivity, Debt, Economic
  • Alternative - Analyst Sentiment, Corporate Governance, Crowding, Insider Activity.

This Python package is automatically generated by the OpenAPI Generator project:

  • API version: 1.0.1
  • SDK version: 1.0.13
  • Build package: org.openapitools.codegen.languages.PythonClientCodegen

For more information, please visit http://www.factset.com/api

Requirements

  • Python >= 3.7

Installation

Poetry

poetry add fds.sdk.utils fds.sdk.FactSetQuantFactorLibrary==1.0.13

pip

pip install fds.sdk.utils fds.sdk.FactSetQuantFactorLibrary==1.0.13

Usage

  1. Generate authentication credentials.
  2. Setup Python environment.
    1. Install and activate python 3.7+. If you're using pyenv:

      pyenv install 3.9.7
      pyenv shell 3.9.7
      
    2. (optional) Install poetry.

  3. Install dependencies.
  4. Run the following:

[!IMPORTANT] The parameter variables defined below are just examples and may potentially contain non valid values. Please replace them with valid values.

Example Code

from fds.sdk.utils.authentication import ConfidentialClient

import fds.sdk.FactSetQuantFactorLibrary
from fds.sdk.FactSetQuantFactorLibrary.api import factors_api
from fds.sdk.FactSetQuantFactorLibrary.models import *
from dateutil.parser import parse as dateutil_parser
from pprint import pprint

# See configuration.py for a list of all supported configuration parameters.

# Examples for each supported authentication method are below,
# choose one that satisfies your use case.

# (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
#
# The confidential client instance should be reused in production environments.
# See https://github.com/FactSet/enterprise-sdk-utils-python#authentication
# for more information on using the ConfidentialClient class
configuration = fds.sdk.FactSetQuantFactorLibrary.Configuration(
    fds_oauth_client=ConfidentialClient('/path/to/app-config.json')
)

# Basic authentication: FactSetApiKey
# See https://github.com/FactSet/enterprise-sdk#api-key
# for information how to create an API key
# configuration = fds.sdk.FactSetQuantFactorLibrary.Configuration(
#     username='USERNAME-SERIAL',
#     password='API-KEY'
# )

# Enter a context with an instance of the API client
with fds.sdk.FactSetQuantFactorLibrary.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = factors_api.FactorsApi(api_client)
    ids = ["FDS-US"] # [str] | Security or Entity identifiers. FactSet Identifiers, tickers, CUSIP and SEDOL are accepted as inputs. **NOTE:** Fixed Income identifiers, ETFs, and Options are not accepted in this endpoint. <p>***Maximum possible ids limit** =  3500 per request*</p> `NOTE:` *The maximum possible ids limit for a request will **decrease** based on the size of the historical date range, the number of factors or factorGroups requested.* *<p> GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \"POST\" method.</p>* 
    factors = ["rsi21D","ulcer252D","turbulence21D"] # [str] | Array of individual Factor Items requested. For a list of all available factors and descriptions use the `/library` endpoint.***<p>factors limit** = 20 individual factors per request* 
    start_date = "2020-11-30" # str | The start date requested for a given date range in **YYYY-MM-DD** format. Future dates (T+1) are not accepted in this endpoint. 
    end_date = "2021-11-30" # str | The end date requested for a given date range in **YYYY-MM-DD** format. Future dates (T+1) are not accepted in this endpoint. **NOTE:** The input endDate must come AFTER the input startDate. 
    factor_groups = ["Momentum","Technical","Volatility"] # [str] | Fetch a collection of Factors that fall within one of the below \"groups\". For example, resting factorGroup=Momentum will return all factors under the momentum group. To know which items are available in each group use the /library endpoint.***<p>factor groups limit** = 5 factor groups per request* ### Classification and Reference |Group|Descriptions| |---|---| |Asset_Data|Easily input security-level metadata into your quantitative research process. Common metrics used include Days Since Report, Days to Report, ADR Flag, and Minimum Lot Size. Integrate variables from FactSet Reference, FactSet Fundamentals, and FactSet Estimates databases to impose portfolio constraints and access general reference data.| |Country|Evaluate securities based on the countries in which they have the highest exposure. Analyze company-level exposures across various countries and measure how concentrated a firm’s business is within their countries of operation. Metrics are derived from FactSet Reference and FactSet Geographic Revenue Exposure (GeoRev) databases and include Country Exposure, Country of Incorporation, and Country of Risk.| |Industry|Classify securities based on the industries in which they generate the majority of their revenues. Incorporate variables from the FactSet Revere Business and Industry Classification System (RBICS) database to measure how concentrated a firm’s business is within the industries they operate and across various sub-sectors. Common metrics include Industry Classifications, Industry Exposures, and Industry Concentration.| |Size|Assess how large or small a company is relative to industry peers. Create size buckets and clarify the systematic portion of company returns using variables from FactSet Prices, FactSet RBICS, FactSet Fundamentals, and FactSet Estimates. Common metrics include Size Classification, Enterprise Value, and Market Share.| ### Market Factors |Group|Descriptions| |---|---| |Liquidity|Assess how investible a security is, as well as the potential market impact of a trade using signals built off pricing and volume data from FactSet Prices. Integrate factors as components into your alpha models to evaluate systematic risk or input them into your portfolio construction models to dictate how much of an asset can be bought or sold based on liquidity levels. Common metrics include Average Dollars Traded, Share Turnover, and Bid Ask Spread.| |Market Sensitivity|Clarify the common variations in stock returns attributable to the performance of their local market indices. Leverage regressions performed between security-level and market-index returns across different return horizons and methodologies. Metrics are derived from FactSet Prices and include Beta R-Squared, Up Market Beta, and Down Market Beta.| |Momentum|Analyze the historical momentum of a security and uncover how each underlying data item, calculation, and horizon can be meaningful in different situations. Metrics are derived from FactSet Prices and include 52W Position, Return Momentum, and Velocity.| |Technical|Forecast the direction of future price movements based on historical market data and leverage heuristic or pattern-based signals from FactSet Prices. Common metrics include Average True Range, Ulcer Performance Index, and Money Flow Volume.| |Volatility|Measure the uncertainty in asset price movements with indicators from the FactSet Prices database. Capture various forms of uncertainty by employing statistical calculations on security performance data. Common metrics include Return Volatility, Semivariance, and Turbulence.| ### Core Fundamentals |Group|Descriptions| |---|---| |Efficiency|Leverage core financial data to determine how effectively a company uses its assets, collects payments, and operates its business. Most variables are measured as turnover ratios and include changes over time to provide transparency into the efficiency of each business process. Metrics are derived from FactSet Fundamentals and FactSet Estimates and include Asset Turnover, Receivables Turnover, and Cash Conversion Cycle| |Growth|Measure a company’s ability to grow faster than its peers. Compare the future expected growth of a company with its historical growth and view growth rates adjusted for stability. Integrate variables from FactSet RBICS, FactSet Fundamentals, and FactSet Estimates to analyze growth rates over multiple horizons including Market Share, Sales, and EPS Growth| |Management|Gain insight into how management finances their business and the decisions they make that impact the core financial statements. These choices are reflected in changes to total debt or equity, the overall size of the balance sheet, and decisions around the accounting methods used. Metrics are derived from FactSet Fundamentals and FactSet Estimates and include Capital Expenditures (CAPEX) Growth, Equity Buyback Ratio, and Depreciation & Amortization Variability| |Profitability|Evaluate a company’s ability to generate income relative to its revenue or balance sheet metrics. Identify lucrative businesses relative to their industry, region, and size profile. Metrics are derived from FactSet Fundamentals and FactSet Estimates and include Return on Assets, Return on Invested Capital Change, and Return on Total Equity |Quality|Understand the overall financial health and quality of a company’s business. Use historical data from FactSet Fundamentals to analyze balance sheet health, stability of earnings and profit margins, variability in cash flows, and trends that look beyond headline financial metrics. Common metrics include Cash Earnings Ratio Variability, Revenue Stability, and Accruals Ratios. Composite quality scores (i.e., the Piotroski F-Score, Beneish M-Score, and Altman Z-Score) and their underlying components are also available as individual metrics.| |Solvency|Measure a company’s ability to meet their short- and long-term financial obligations and determine the degree of leverage employed to run their business. Incorporate financial ratios from FactSet Fundamentals and FactSet Estimates to quantify liability or debt obligation relative to earnings, cash flows, equities, or items from the asset side of the balance sheet. Common metrics include Current Ratio, Current Asset Liquidity, and Debt to Equity Change.| |Value|Quickly determine how cheap or expensive a company is based on common security-level characteristics from FactSet Prices, FactSet Fundamentals, and FactSet Estimates. Apply factors as an intersection between other factors for a more customized analysis, such as finding the cheapest stocks among the highest quality companies. Common metrics include Earnings Yield, Book to Price, and Revenue to Enterprise Value.| ### Macro and Cross-Asset |Group|Descriptions| |---|---| |Commodity|Quantify the impact movements in the commodity markets have on equity prices. Metrics are derived from FactSet Prices and allow you to measure company-level exposure to commodities such as Gold, Crude Oil, Coffee, and Live Cattle.| |FX_Sensitivity| Analyze security-level sensitivity to fluctuations in the currency markets. Metrics are derived from FactSet Prices and allow you to identify company exposures to currencies such as USD, EUR, JPY, and CNY. |Debt|Uncover details related to company debt through issuer-level factor exposures. Use the FactSet Fixed Income Prices & Derived Analytics database to aggregate metrics at the company level. Common metrics include Effective Duration, Option Adjusted Spread, and Yield to Worst.| |Economic|Capture daily security exposures to leading economic indicator forecasts. Leverage the Quant Factor Library’s detailed country exposure model to attribute economic measures to individual companies. Metrics are derived from FactSet Economic Estimates and include Real GPD Growth, Industrial Production Growth, Core CPI Inflation, and Policy Rates. ### Alternative |Group|Descriptions| |---|---| |Analyst_Sentiment|Analyze a security’s outlook from the perspective of a sell-side research analyst. Leverage consensus estimates data from the FactSet Estimates database to analyze the directional change in estimate revisions for various financial statement items and time periods. Common metrics include Sales Estimate Revisions, Free Cash Flow Estimate Revisions, and Robust Estimate Revisions.| |Corporate_Governance|Identify companies with strong corporate governance. Analyze the profile of a company’s management and board based on tenure, diversity, compensation incentives, and more factors from the FactSet People database. Common metrics include Management - Average Age, Board - Activist Member, and Executives - Average Bonus.| |Crowding|Understand the degree to which investors own, purchase, or sell a security. View characteristics of each investor’s profile and characterize crowding from passive, active, institutional, ETF, and hedge fund investors. Use metrics from FactSet Ownership, FactSet Prices, and FactSet Fundamentals to help identify potential effects of crowding such as whether certain investor types are acquiring or divesting from a given security. Common metrics include Active Buyer Percent of Portfolio Change, ETF Days to Liquidate, and Hedge Fund Percent Outstanding.| |Insider_Activity|Measure the degree to which insiders own, purchase, or sell their company’s stock. Analyze the sentiment of those with access to material non-public information or determine how the amount of insider ownership may impact management’s key business decisions. Metrics are derived from FactSet Ownership and include Insider Percent Outstanding, Insider Number of Buys, and Insider Seller Position Change. |ESG|Analyze Environmental, Social and Governance (ESG) behavior, which are aggregated and categorized into continuously updated, material ESG scores to uncover risks and opportunities from companies. Truvalue Labs focuses on company ESG behavior from external sources and includes both positive and negative events that go beyond traditional sources of ESG risk data.  (optional)
    frequency = "M" # str | Controls the display frequency of the data returned.   * **D** = Daily   * **W** = Weekly, based on the last day of the week of the start date.   * **M** = Monthly, based on the last trading day of the month.   * **AM** = Monthly, based on the start date (e.g., if the start date is June 16, data is displayed for June 16, May 16, April 16 etc.).   * **CQ** = Quarterly based on the last trading day of the calendar quarter (March, June, September, or December).   * **AY** = Actual Annual, based on the start date.   * **CY** = Calendar Annual, based on the last trading day of the calendar year.  (optional) if omitted the server will use the default value of "M"

    try:
        # Retrieves Quant Factors for a small list of ids.
        # example passing only required values which don't have defaults set
        # and optional values
        api_response = api_instance.get_factors(ids, factors, start_date, end_date, factor_groups=factor_groups, frequency=frequency)

        pprint(api_response)
    except fds.sdk.FactSetQuantFactorLibrary.ApiException as e:
        print("Exception when calling FactorsApi->get_factors: %s\n" % e)

    # # Get response, http status code and response headers
    # try:
    #     # Retrieves Quant Factors for a small list of ids.
    #     api_response, http_status_code, response_headers = api_instance.get_factors_with_http_info(ids, factors, start_date, end_date, factor_groups=factor_groups, frequency=frequency)


    #     pprint(api_response)
    #     pprint(http_status_code)
    #     pprint(response_headers)
    # except fds.sdk.FactSetQuantFactorLibrary.ApiException as e:
    #     print("Exception when calling FactorsApi->get_factors: %s\n" % e)

    # # Get response asynchronous
    # try:
    #     # Retrieves Quant Factors for a small list of ids.
    #     async_result = api_instance.get_factors_async(ids, factors, start_date, end_date, factor_groups=factor_groups, frequency=frequency)
    #     api_response = async_result.get()


    #     pprint(api_response)
    # except fds.sdk.FactSetQuantFactorLibrary.ApiException as e:
    #     print("Exception when calling FactorsApi->get_factors: %s\n" % e)

    # # Get response, http status code and response headers asynchronous
    # try:
    #     # Retrieves Quant Factors for a small list of ids.
    #     async_result = api_instance.get_factors_with_http_info_async(ids, factors, start_date, end_date, factor_groups=factor_groups, frequency=frequency)
    #     api_response, http_status_code, response_headers = async_result.get()


    #     pprint(api_response)
    #     pprint(http_status_code)
    #     pprint(response_headers)
    # except fds.sdk.FactSetQuantFactorLibrary.ApiException as e:
    #     print("Exception when calling FactorsApi->get_factors: %s\n" % e)

Using Pandas

To convert an API response to a Pandas DataFrame, it is necessary to transform it first to a dictionary.

import pandas as pd

response_dict = api_response.to_dict()['data']

simple_json_response = pd.DataFrame(response_dict)
nested_json_response = pd.json_normalize(response_dict)

Debugging

The SDK uses the standard library logging module.

Setting debug to True on an instance of the Configuration class sets the log-level of related packages to DEBUG and enables additional logging in Pythons HTTP Client.

Note: This prints out sensitive information (e.g. the full request and response). Use with care.

import logging
import fds.sdk.FactSetQuantFactorLibrary

logging.basicConfig(level=logging.DEBUG)

configuration = fds.sdk.FactSetQuantFactorLibrary.Configuration(...)
configuration.debug = True

Configure a Proxy

You can pass proxy settings to the Configuration class:

  • proxy: The URL of the proxy to use.
  • proxy_headers: a dictionary to pass additional headers to the proxy (e.g. Proxy-Authorization).
import fds.sdk.FactSetQuantFactorLibrary

configuration = fds.sdk.FactSetQuantFactorLibrary.Configuration(
    # ...
    proxy="http://secret:password@localhost:5050",
    proxy_headers={
        "Custom-Proxy-Header": "Custom-Proxy-Header-Value"
    }
)

Custom SSL Certificate

TLS/SSL certificate verification can be configured with the following Configuration parameters:

  • ssl_ca_cert: a path to the certificate to use for verification in PEM format.
  • verify_ssl: setting this to False disables the verification of certificates. Disabling the verification is not recommended, but it might be useful during local development or testing.
import fds.sdk.FactSetQuantFactorLibrary

configuration = fds.sdk.FactSetQuantFactorLibrary.Configuration(
    # ...
    ssl_ca_cert='/path/to/ca.pem'
)

Request Retries

In case the request retry behaviour should be customized, it is possible to pass a urllib3.Retry object to the retry property of the Configuration.

from urllib3 import Retry
import fds.sdk.FactSetQuantFactorLibrary

configuration = fds.sdk.FactSetQuantFactorLibrary.Configuration(
    # ...
)

configuration.retries = Retry(total=3, status_forcelist=[500, 502, 503, 504])

Documentation for API Endpoints

All URIs are relative to https://api.factset.com/content

Class Method HTTP request Description
FactorsApi get_factors GET /factset-quant-factor-library/v1/factors Retrieves Quant Factors for a small list of ids.
FactorsApi get_factors_for_list POST /factset-quant-factor-library/v1/factors Retrieves Quant Factors for a large list of ids.
HelperApi get_factor_library GET /factset-quant-factor-library/v1/library Retrieve a list of all available factors with relevant meta data.
HelperApi get_factor_library_list POST /factset-quant-factor-library/v1/library Retrieves a list of all available factors with relevant meta data.

Documentation For Models

Documentation For Authorization

FactSetApiKey

  • Type: HTTP basic authentication

FactSetOAuth2

  • Type: OAuth
  • Flow: application
  • Authorization URL:
  • Scopes: N/A

Notes for Large OpenAPI documents

If the OpenAPI document is large, imports in fds.sdk.FactSetQuantFactorLibrary.apis and fds.sdk.FactSetQuantFactorLibrary.models may fail with a RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions:

Solution 1: Use specific imports for apis and models like:

  • from fds.sdk.FactSetQuantFactorLibrary.api.default_api import DefaultApi
  • from fds.sdk.FactSetQuantFactorLibrary.model.pet import Pet

Solution 2: Before importing the package, adjust the maximum recursion limit as shown below:

import sys
sys.setrecursionlimit(1500)
import fds.sdk.FactSetQuantFactorLibrary
from fds.sdk.FactSetQuantFactorLibrary.apis import *
from fds.sdk.FactSetQuantFactorLibrary.models import *

Contributing

Please refer to the contributing guide.

Copyright

Copyright 2022 FactSet Research Systems Inc

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

File details

Details for the file fds.sdk.FactSetQuantFactorLibrary-1.0.13.tar.gz.

File metadata

  • Download URL: fds.sdk.FactSetQuantFactorLibrary-1.0.13.tar.gz
  • Upload date:
  • Size: 79.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.10.0 readme-renderer/34.0 requests/2.27.1 requests-toolbelt/1.0.0 urllib3/1.26.20 tqdm/4.64.1 importlib-metadata/4.8.3 keyring/23.4.1 rfc3986/1.5.0 colorama/0.4.5 CPython/3.6.15

File hashes

Hashes for fds.sdk.FactSetQuantFactorLibrary-1.0.13.tar.gz
Algorithm Hash digest
SHA256 8b3263d49c41cae866f7709f8d329ad56616d5e1a70f346b516ada7a03459b73
MD5 ac12ef4e56feb61f1206dda4bdaa9ecb
BLAKE2b-256 aed8babf6ff7d675e95ee9fcd4ad950fdba095489b4ea4a027ec2f1556f9ced2

See more details on using hashes here.

File details

Details for the file fds.sdk.FactSetQuantFactorLibrary-1.0.13-py3-none-any.whl.

File metadata

  • Download URL: fds.sdk.FactSetQuantFactorLibrary-1.0.13-py3-none-any.whl
  • Upload date:
  • Size: 104.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.10.0 readme-renderer/34.0 requests/2.27.1 requests-toolbelt/1.0.0 urllib3/1.26.20 tqdm/4.64.1 importlib-metadata/4.8.3 keyring/23.4.1 rfc3986/1.5.0 colorama/0.4.5 CPython/3.6.15

File hashes

Hashes for fds.sdk.FactSetQuantFactorLibrary-1.0.13-py3-none-any.whl
Algorithm Hash digest
SHA256 0b9050192d3599a473925193d270783936efbd217d4b864173d0be9ce7931351
MD5 63bda89be470e9d77359e6915fe9a29c
BLAKE2b-256 fe96f2e19c20cc63d4ec671ad8624ea44b6091c8a395c36c1c427cb117921a53

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page