### API Overview: Twelve Data API Source: https://api.twelvedata.com/doc/swagger/openapi.json ## Overview Welcome to Twelve Data developer docs — your gateway to comprehensive financial market data through a powerful and easy-to-use API. Twelve Data provides access to financial markets across over 50 global countries, covering more than 1 million public instruments, including stocks, forex, ETFs, mutual funds, commodities, and cryptocurrencies. ## Quickstart To get started, you'll need to sign up for an API key. Once you have your API key, you can start making requests to the API. ### Step 1: Create Twelve Data account Sign up on the Twelve Data website to create your account [here](https://twelvedata.com/register). This gives you access to the API dashboard and your API key. ### Step 2: Get your API key After signing in, navigate to your [dashboard](https://twelvedata.com/account/api-keys) to find your unique API key. This key is required to authenticate all API and WebSocket requests. ### Step 3: Make your first request Try a simple API call with cURL to fetch the latest price for Apple (AAPL): ``` curl "https://api.twelvedata.com/price?symbol=AAPL&apikey=your_api_key" ``` ### Step 4: Make a request from Python or Javascript Use our client libraries or standard HTTP clients to make API calls programmatically. Here’s an example in [Python](https://github.com/twelvedata/twelvedata-python) and [Node.js](https://github.com/twelvedata/twelvedata-node): #### Python (using official Twelve Data SDK): ```python from twelvedata import TDClient # Initialize client with your API key td = TDClient(apikey="your_api_key") # Get latest price for Apple price = td.price(symbol="AAPL").as_json() print(price) ``` #### JavaScript (Node.js): ```javascript import { MarketDataApi, CreateConfig } from "@twelvedata/twelvedata-node"; const config = CreateConfig('your_api_key'); const api = new MarketDataApi(config); async function main() {   const response = await api.getPrice({     symbol: "AAPL",   });   console.log(response.data); } main().catch(console.error); ``` ### Step 5: Perform correlation analysis between Tesla and Microsoft prices Fetch historical price data for Tesla (TSLA) and Microsoft (MSFT) and calculate the correlation of their closing prices: ```python from twelvedata import TDClient import pandas as pd # Initialize client with your API key td = TDClient(apikey="your_api_key") # Fetch historical price data for Tesla tsla_ts = td.time_series(     symbol="TSLA",     interval="1day",     outputsize=100 ).as_pandas() # Fetch historical price data for Microsoft msft_ts = td.time_series(     symbol="MSFT",     interval="1day",     outputsize=100 ).as_pandas() # Align data on datetime index combined = pd.concat(     [tsla_ts['close'].astype(float), msft_ts['close'].astype(float)],     axis=1,     keys=["TSLA", "MSFT"] ).dropna() # Calculate correlation correlation = combined["TSLA"].corr(combined["MSFT"]) print(f"Correlation of closing prices between TSLA and MSFT: {correlation:.2f}") ``` ### Authentication Authenticate your requests using one of these methods: #### Query parameter method ``` GET https://api.twelvedata.com/endpoint?symbol=AAPL&apikey=your_api_key ``` #### HTTP header method (recommended) ``` Authorization: apikey your_api_key ``` ##### API key useful information ### API endpoints Service | Base URL | ---------|----------| REST API | `https://api.twelvedata.com` | WebSocket | `wss://ws.twelvedata.com` | ### Parameter guidelines ### Response handling #### Default format All responses return JSON format by default unless otherwise specified. #### Null values Important: Some response fields may contain `null` values when data is unavailable for specific metrics. This is expected behavior, not an error. ##### Best Practices: #### Error handling Structure your code to gracefully handle: ##### Best practices ## Errors Twelve Data API employs a standardized error response format, delivering a JSON object with `code`, `message`, and `status` keys for clear and consistent error communication. ### Codes Below is a table of possible error codes, their HTTP status, meanings, and resolution steps: Code | status | Meaning | Resolution | --- | --- | --- | --- | **400** | Bad Request | Invalid or incorrect parameter(s) provided. | Check the `message` in the response for details. Refer to the API Documenta­tion to correct the input. | **401** | Unauthor­ized | Invalid or incorrect API key. | Verify your API key is correct. Sign up for a key here. | **403** | Forbidden | API key lacks permissions for the requested resource (upgrade required). | Upgrade your plan here. | **404** | Not Found | Requested data could not be found. | Adjust parameters to be less strict as they may be too restrictive. | **414** | Parameter Too Long | Input parameter array exceeds the allowed length. | Follow the `message` guidance to adjust the parameter length. | **429** | Too Many Requests | API request limit reached for your key. | Wait briefly or upgrade your plan here. | **500** | Internal Server Error | Server-side issue occurred; retry later. | Contact support here for assistance. | ### Example error response Consider the following invalid request: ``` https://api.twelvedata.com/time_series?symbol=AAPL&interval=0.99min&apikey=your_api_key ``` Due to the incorrect `interval` value, the API returns: ```json {   "code": 400,   "message": "Invalid **interval** provided: 0.99min. Supported intervals: 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month",   "status": "error" } ``` Refer to the API Documentation for valid parameter values to resolve such errors. ## Libraries Twelve Data provides a growing ecosystem of libraries and integrations to help you build faster and smarter in your preferred environment. Official libraries are actively maintained by the Twelve Data team, while selected community-built libraries offer additional flexibility. A full list is available on our [GitHub profile](https://github.com/search?q=twelvedata). ### Official SDKs ### AI integrations ### Spreadsheet add-ons ### Community libraries The community has developed libraries in several popular languages. You can explore more community libraries on [GitHub](https://github.com/search?q=twelvedata). ### Other Twelve Data repositories ### API specification ```yaml # Twelve Data API # Version: 0.0.1 ## Overview Welcome to Twelve Data developer docs — your gateway to comprehensive financial market data through a powerful and easy-to-use API. Twelve Data provides access to financial markets across over 50 global countries, covering more than 1 million public instruments, including stocks, forex, ETFs, mutual funds, commodities, and cryptocurrencies. ## Quickstart To get started, you'll need to sign up for an API key. Once you have your API key, you can start making requests to the API. ### Step 1: Create Twelve Data account Sign up on the Twelve Data website to create your account [here](https://twelvedata.com/register). This gives you access to the API dashboard and your API key. ### Step 2: Get your API key After signing in, navigate to your [dashboard](https://twelvedata.com/account/api-keys) to find your unique API key. This key is required to authenticate all API and WebSocket requests. ### Step 3: Make your first request Try a simple API call with cURL to fetch the latest price for Apple (AAPL): ``` curl "https://api.twelvedata.com/price?symbol=AAPL&apikey=your_api_key" ``` ### Step 4: Make a request from Python or Javascript Use our client libraries or standard HTTP clients to make API calls programmatically. Here’s an example in [Python](https://github.com/twelvedata/twelvedata-python) and [Node.js](https://github.com/twelvedata/twelvedata-node): #### Python (using official Twelve Data SDK): ```python from twelvedata import TDClient # Initialize client with your API key td = TDClient(apikey="your_api_key") # Get latest price for Apple price = td.price(symbol="AAPL").as_json() print(price) ``` #### JavaScript (Node.js): ```javascript import { MarketDataApi, CreateConfig } from "@twelvedata/twelvedata-node"; const config = CreateConfig('your_api_key'); const api = new MarketDataApi(config); async function main() {   const response = await api.getPrice({     symbol: "AAPL",   });   console.log(response.data); } main().catch(console.error); ``` ### Step 5: Perform correlation analysis between Tesla and Microsoft prices Fetch historical price data for Tesla (TSLA) and Microsoft (MSFT) and calculate the correlation of their closing prices: ```python from twelvedata import TDClient import pandas as pd # Initialize client with your API key td = TDClient(apikey="your_api_key") # Fetch historical price data for Tesla tsla_ts = td.time_series(     symbol="TSLA",     interval="1day",     outputsize=100 ).as_pandas() # Fetch historical price data for Microsoft msft_ts = td.time_series(     symbol="MSFT",     interval="1day",     outputsize=100 ).as_pandas() # Align data on datetime index combined = pd.concat(     [tsla_ts['close'].astype(float), msft_ts['close'].astype(float)],     axis=1,     keys=["TSLA", "MSFT"] ).dropna() # Calculate correlation correlation = combined["TSLA"].corr(combined["MSFT"]) print(f"Correlation of closing prices between TSLA and MSFT: {correlation:.2f}") ``` ### Authentication Authenticate your requests using one of these methods: #### Query parameter method ``` GET https://api.twelvedata.com/endpoint?symbol=AAPL&apikey=your_api_key ``` #### HTTP header method (recommended) ``` Authorization: apikey your_api_key ``` ##### API key useful information ### API endpoints Service | Base URL | ---------|----------| REST API | `https://api.twelvedata.com` | WebSocket | `wss://ws.twelvedata.com` | ### Parameter guidelines ### Response handling #### Default format All responses return JSON format by default unless otherwise specified. #### Null values Important: Some response fields may contain `null` values when data is unavailable for specific metrics. This is expected behavior, not an error. ##### Best Practices: #### Error handling Structure your code to gracefully handle: ##### Best practices ## Errors Twelve Data API employs a standardized error response format, delivering a JSON object with `code`, `message`, and `status` keys for clear and consistent error communication. ### Codes Below is a table of possible error codes, their HTTP status, meanings, and resolution steps: Code | status | Meaning | Resolution | --- | --- | --- | --- | **400** | Bad Request | Invalid or incorrect parameter(s) provided. | Check the `message` in the response for details. Refer to the API Documenta­tion to correct the input. | **401** | Unauthor­ized | Invalid or incorrect API key. | Verify your API key is correct. Sign up for a key here. | **403** | Forbidden | API key lacks permissions for the requested resource (upgrade required). | Upgrade your plan here. | **404** | Not Found | Requested data could not be found. | Adjust parameters to be less strict as they may be too restrictive. | **414** | Parameter Too Long | Input parameter array exceeds the allowed length. | Follow the `message` guidance to adjust the parameter length. | **429** | Too Many Requests | API request limit reached for your key. | Wait briefly or upgrade your plan here. | **500** | Internal Server Error | Server-side issue occurred; retry later. | Contact support here for assistance. | ### Example error response Consider the following invalid request: ``` https://api.twelvedata.com/time_series?symbol=AAPL&interval=0.99min&apikey=your_api_key ``` Due to the incorrect `interval` value, the API returns: ```json {   "code": 400,   "message": "Invalid **interval** provided: 0.99min. Supported intervals: 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month",   "status": "error" } ``` Refer to the API Documentation for valid parameter values to resolve such errors. ## Libraries Twelve Data provides a growing ecosystem of libraries and integrations to help you build faster and smarter in your preferred environment. Official libraries are actively maintained by the Twelve Data team, while selected community-built libraries offer additional flexibility. A full list is available on our [GitHub profile](https://github.com/search?q=twelvedata). ### Official SDKs ### AI integrations ### Spreadsheet add-ons ### Community libraries The community has developed libraries in several popular languages. You can explore more community libraries on [GitHub](https://github.com/search?q=twelvedata). ### Other Twelve Data repositories ### API specification # Base URL: https://api.twelvedata.com/ ``` -------------------------------- ### GET /earliest_timestamp Source: https://api.twelvedata.com/doc/swagger/openapi.json The earliest_timestamp endpoint provides the earliest available date and time for a specified financial instrument at a given data interval. This endpoint is useful for determining the starting point of historical data availability for various assets, such as stocks or currencies, allowing users to understand the time range covered by the data. ```markdown ### Parameters - **symbol** (string, query, optional): Symbol ticker of the instrument. - **figi** (string, query, optional): Filter by financial instrument global identifier (FIGI). This parameter is available on the Ultra plan (individual) and the Enterprise plan (business) and above. - **isin** (string, query, optional): Filter by international securities identification number (ISIN). ISIN access is activating in the Data add-ons section - **cusip** (string, query, optional): The CUSIP of an instrument for which data is requested. CUSIP access is activating in the Data add-ons section - **interval** (IntervalEnum, query, required): Interval between two consecutive points in time series. - **exchange** (string, query, optional): Exchange where instrument is traded. - **mic_code** (string, query, optional): Market Identifier Code (MIC) under ISO 10383 standard. - **timezone** (string, query, optional): Timezone at which output datetime will be displayed. Supports:

Interval Limitation: The timezone parameter is only applicable for intraday intervals (less than 1 day). For intervals of 1day, 1week, or 1month, the timezone parameter is ignored, and data is strictly returned in the Exchange local time.

Take note that the IANA Timezone name is case-sensitive ### Responses #### 200 - response **GetEarliestTimestamp_200_response** - **datetime** (string) (required): Earliest datetime, the format depends on interval - **unix_time** (integer (int64)) (required): Datetime converted to UNIX timestamp #### 400 - response **ApiBadRequestErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 401 - response **ApiUnauthorizedErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 403 - response **ApiForbiddenErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 404 - response **ApiNotFoundErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 414 - response **ApiParameterTooLongErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 429 - response **ApiTooManyRequestsErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 500 - response **ApiInternalServerErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status ### Example Usage ```bash curl -X GET "https://api.twelvedata.com//earliest_timestamp?symbol=string&figi=string&isin=string&cusip=string&interval=value&exchange=string&mic_code=string&timezone=Exchange" ``` ``` -------------------------------- ### POST /batch Source: https://api.twelvedata.com/doc/swagger/openapi.json The batch request endpoint allows users to request data for multiple financial instruments, time intervals, and data types simultaneously. This endpoint is useful for efficiently gathering diverse financial data in a single operation, reducing the need for multiple individual requests. Errors in specific requests do not affect the processing of others, and each error is reported separately, enabling easy troubleshooting. ### Request body Only JSON `POST` requests are supported. The request content structure consists of key-value items. The key is a unique request ID. The value is requested url. ### Response The response contains key-value data. The key is a unique request ID. The value is returned data. ### API credits ```markdown ### Request Body **Content-Type:** application/json **Content-Type:** application/xml ### Responses #### 200 - response **advanced_200_response** - **code** (integer (int64)): HTTP status code - **status** (string): Status of the request - **data** (object): Response data containing individual request results #### 400 - response **ApiBadRequestErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 401 - response **ApiUnauthorizedErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 403 - response **ApiForbiddenErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 404 - response **ApiNotFoundErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 414 - response **ApiParameterTooLongErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 429 - response **ApiTooManyRequestsErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 500 - response **ApiInternalServerErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status ### Example Usage ```bash curl -X POST "https://api.twelvedata.com//batch" \ -H "Content-Type: application/json" \ -d '"value"' ``` ``` -------------------------------- ### GET /linearregintercept Source: https://api.twelvedata.com/doc/swagger/openapi.json The Linear Regression Intercept endpoint (LINEARREGINTERCEPT) calculates the y-intercept of a linear regression line for a given dataset. It returns the value where the regression line crosses the y-axis, providing a numerical reference point for understanding the starting position of a trend over a specified period. This can be useful for users needing to establish baseline values in their data analysis. ```markdown ### Parameters - **symbol** (string, query, optional): Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ... - **isin** (string, query, optional): Filter by international securities identification number (ISIN). ISIN access is activating in the Data add-ons section - **figi** (string, query, optional): The FIGI of an instrument for which data is requested. This parameter is available on the Ultra plan (individual) and the Enterprise plan (business) and above. - **cusip** (string, query, optional): The CUSIP of an instrument for which data is requested. CUSIP access is activating in the Data add-ons section - **interval** (IntervalEnum, query, required): Interval between two consecutive points in time series - **outputsize** (integer (int64), query, optional): Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum - **exchange** (string, query, optional): Exchange where instrument is traded - **mic_code** (string, query, optional): Market Identifier Code (MIC) under ISO 10383 standard - **country** (string, query, optional): The country where the instrument is traded, e.g., `United States` or `US` - **type** (TypeEnum, query, optional): The asset class to which the instrument belongs - **timezone** (string, query, optional): Timezone at which output datetime will be displayed. Supports:

Interval Limitation: The timezone parameter is only applicable for intraday intervals (less than 1 day). For intervals of 1day, 1week, or 1month, the timezone parameter is ignored, and data is strictly returned in the Exchange local time.

Take note that the IANA Timezone name is case-sensitive - **start_date** (string, query, optional): Can be used separately and together with `end_date`. Format `2006-01-02` or `2006-01-02T15:04:05` Default location: Both parameters take into account if timezone parameter is provided.
If timezone is given then, start_date and end_date will be used in the specified location Examples: - **end_date** (string, query, optional): The ending date and time for data selection, see `start_date` description for details. - **date** (string, query, optional): Specifies the exact date to get the data for. Could be the exact date, e.g. `2021-10-27`, or in human language `today` or `yesterday` - **order** (OrderEnum, query, optional): Sorting order of the output - **prepost** (boolean, query, optional): Returns quotes that include pre-market and post-market data. Only for the `Pro` plan (individual) and `Venture` plan (business) and above. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume - **format** (FormatEnum, query, optional): The format of the response data - **delimiter** (string, query, optional): The separator used in the CSV response data - **dp** (integer (int64), query, optional): Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive. By default, the number of decimal places is automatically determined based on the values provided - **previous_close** (boolean, query, optional): A boolean parameter to include the previous closing price in the time_series data. If true, adds previous bar close price value to the current object - **adjust** (AdjustEnum, query, optional): Adjusting mode for prices - **series_type** (SeriesTypeEnum, query, optional): Price type on which technical indicator is calculated - **time_period** (integer (int64), query, optional): Number of periods to average over. Takes values in the range from `1` to `800` - **include_ohlc** (boolean, query, optional): Specify if OHLC values should be added in the output ### Responses #### 200 - response **GetTimeSeriesLinearRegIntercept_200_response** - **meta** (object) (required): Common metadata fields for time series indicator responses - **symbol** (string): The ticker symbol of an instrument for which data was requested. - **interval** (string): The time gap between consecutive data points. - **currency** (string): The currency of a traded instrument. - **exchange_timezone** (string): The timezone of the exchange where the instrument is traded. - **exchange** (string): The exchange name where the instrument is traded. - **mic_code** (string): The Market Identifier Code (MIC) of the exchange where the instrument is traded. - **type** (string): The asset class to which the instrument belongs. - **indicator** (object): Technical indicator information - **name** (string) (required): Name of the technical indicator - **series_type** (string) (required): Price type on which technical indicator is calculated - **time_period** (integer (int64)) (required): Number of periods to average over - **values** (array (GetTimeSeriesLinearRegIntercept_200_response_values_inner)) (required): Array of time series data points Array items: - **datetime** (string) (required): Datetime in local market time for equities and in UTC for forex and cryptocurrencies referring to when the bar with specified interval was opened - **linearregintercept** (string) (required): Linear Regression Intercept value - **status** (string) (required): Response status #### 400 - response **ApiBadRequestErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 401 - response **ApiUnauthorizedErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 403 - response **ApiForbiddenErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 404 - response **ApiNotFoundErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 414 - response **ApiParameterTooLongErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 429 - response **ApiTooManyRequestsErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status #### 500 - response **ApiInternalServerErrorResponseBody** - **code** (integer (int64)) (required): Error code - **message** (string) (required): Error message - **status** (string) (required): Error status ### Example Usage ```bash curl -X GET "https://api.twelvedata.com//linearregintercept?symbol=string&isin=string&figi=string&cusip=string&interval=value&outputsize=30&exchange=string&mic_code=string&country=string&type=value&timezone=Exchange&start_date=string&end_date=string&date=string&order=value&prepost=false&format=value&delimiter=;&dp=-1&previous_close=false&adjust=value&series_type=value&time_period=9&include_ohlc=false" ``` ```