Master the Twelve Data API with Python: A Comprehensive Tutorial

Keen on automating your trading or enhancing your financial data analysis? Our Twelve Data API Python tutorial is your one-stop solution!

We walk you through every step, from harnessing historical data to real-time streaming via WebSockets. Our tutorial fills in the gaps left by the official documentation, giving you insights you won’t find anywhere else.

This article is the how-to guide; if you’re interested in the review, check out my comprehensive Twelve Data Review.

What Is Twelve Data?

Twelve Data is a powerful financial data platform that provides users access to real-time and historical market data for various financial instruments. With its user-friendly API, Twelve Data enables developers to quickly and easily integrate financial data into their Python applications.

Twelve Data was founded in 2018 and is headquartered in Singapore, Singapore.

Setting Up Twelve Data Python API Library

To use Twelve Data API endpoints, sign up for the Twelve Data account and get your API Key. You can then use the Python twelvedata library or Python requests module to call Twelve Data API endpoints. You will see both approaches in this section.

Signing Up for a Twelve Data Account

To sign up for the free basic plan, go to the Twelve Data account sign-up page and create your account. You will need to enter your name, email address, and password. You will receive a verification email. Verifying your email address takes you to the Twelve Data account dashboard.

Fetching Twelve Data API Key

From the left sidebar on the dashboard, click “API Keys.” Click the “reveal” button on the main window to see your free API key. Save your API key in a secure location. I recommend using environment variables.

Installing Twelve Data Python Library

You can install the twelvedata Python library with the following three commands. I recommend using the third command as it installs the twelvedata library and various other dependencies with a single command.

pip install twelvedata

pip install twelvedata[pandas]

pip install twelvedata[pandas,matplotlib,plotly,websocket-client]

Fetching Data Using Twelve Data API in Python

You can retrieve data from Twelve Data API via the Python twelvedata library or the requests module.  

Fetching Data Using the Python twelvedata Library

To fetch data using the twelvedata library, you must create an object of the TDClient class from the twelvedata module. Pass your API key to the apikey attribute of the TDClient class constructor.

The TDClient object provides several methods to call Twelve Data API endpoints. For instance, the following script employs the time_series() method to retrieve time series OHLCV data for a stock.

The as_pands() method of the ts (time_series) object returns the data in a Pandas DataFrame.

import os
api_key = os.environ['TD_KEY']
from twelvedata import TDClient

# Initialize client - apikey parameter is required
td = TDClient(apikey = api_key)

# Construct the necessary time series
ts = td.time_series(
    symbol="AAPL",
    interval="1min",
    outputsize=5
)

# Returns pandas.DataFrame
ts.as_pandas()

Fetching Data Using Python Requests Module

The twelve Data API doesn’t implement some of the Twelve Data API endpoints, as you will see later in the article. You can use the Python requests module to retrieve data from these endpoints. The requests module is faster compared to the Python twelvedata library.

If response time and speed are your concern, I recommend using the requests module. Otherwise, stick to the twelvedata library, as I find it easier.

The following script demonstrates the requests module’s ability to retrieve time series OHLCV values from Twelve Data API.  

There are three essential parts of an API call via the requests module.  

  1. The base URL for the API: https://api.twelvedata.com.
  2. The endpoint URL, e.g., ‘/time_series?
  3. The parameter values; separated by an ampersand (&) sign.
import requests
import json
import pandas as pd
base_url = 'https://api.twelvedata.com'
endpoint = '/time_series?'
interval = '1min'
symbol = 'AAPL'
outputsize = 5
query = 'apikey={}&interval={}&symbol={}&outputsize={}'.format(api_key,
                                                              interval,
                                                              symbol,
                                                              outputsize)
response = requests.get(base_url + endpoint + query)
response.json()

The requests module returns responses in JSON format, which you can convert into a Python dictionary using the json() method of the response object. Next, you can use the from_records() method of the Pandas DataFrame object to convert the Python dictionary into a Pandas dataframe.

response_df = pd.DataFrame.from_records(response.json()['values'])
response_df.head()

Twelve Data API Endpoints

Per the official documentation, Twelve Data API offers the following list of endpoints, except the Charts endpoint. The Python twelvedata library API documentation includes Charts in the list of endpoints. You will see these endpoints in action in the next sections.

  • Reference Data
  • Core Data
  • Fundamentals
  • Technical Indicators
  • Charts
  • WebSocket
  • Analysis
  • Mutual Funds

The access to these endpoint functions depends upon your subscription type. However, you can try all these endpoints with the free plan using Twelve Data trial symbols.

Reference Data

The reference data endpoint contains methods returning various reference values, e.g., stock lists, cryptocurrency lists, exchanges, etc. You can use this information while calling other endpoints.

Get Stocks List

The get_stocks_list() method returns a list of all stocks accessible through Twelve Data.

td = TDClient(apikey = api_key)
response = td.get_stocks_list().as_json()
response_df = pd.DataFrame.from_records(response)
print(response_df.shape)
response_df.head()

You can filter stocks by country by passing a three-digit country code to the country attribute of the get_stocks_list() method. The following script returns all stocks operating in the USA.

response = td.get_stocks_list(country = "USA")
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

You can filter stocks by exchange name using the exchange attribute. The following script returns all stocks from the New York Stock Exchange.

response = td.get_stocks_list(exchange = "NYSE")
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Get Forex Pairs List

The forex_pairs_list() method returns a list of all Twelve Data forex pairs.

response = td.get_forex_pairs_list()
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

You can filter forex pairs using base or quote currencies. For example, the following code returns all forex pairs having the Euro as their base currencies.

response = td.get_forex_pairs_list(currency_base = "EUR")
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Get Exchanges List

You can retrieve a list of all exchanges using the get_exchanges_list() method.

response = td.get_exchanges_list()
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Like stocks, you can filter exchanges by country using the country attribute of the get_exchanges_list() method.

response = td.get_exchanges_list(country = "USA")
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Get Cryptocurrencies List

The get_cryptocurrencies_list() method returns a list of all cryptocurrencies.

response = td.get_cryptocurrencies_list()
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Like forex pairs, you can filter cryptocurrencies using currency_base and currency_quotes attributes. For example, the script below returns all cryptocurrencies with Ethereum as their quote currencies.

response = td.get_cryptocurrencies_list(currency_quote = "ETH")
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Get Cryptocurrency Exchanges List

The get_cryptocurrency_exchanges_list() method returns a list of all cryptocurrency exchanges.

response = td.get_cryptocurrency_exchanges_list()
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Search Symbols

The search_symbol() method retrieves best matching instruments from Twelve Data. The response returns the most relevant instruments at the top of the list.

response = td.symbol_search(symbol = "apple")
response_df = pd.DataFrame.from_records(response.as_json())
print(response_df.shape)
response_df.head()

Core Data

The core data endpoint returns core financial data such as time series OHLCV for a stock, exchange rates, real-time and end-of-day prices, etc.

Time Series

The time_series() method returns time series OHLCV data for a stock. In a previous section, you have seen the time_series() method in action.

Let’s see some of its common attributes.

The interval parameter of the time_series() method specifies the interval of the data points you want to retrieve. The valid values are 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month.

The output_size parameter specifies the number of data points to retrieve.

ts = td.time_series(
    symbol="AAPL",
    interval="1min",
    outputsize=5
)

ts.as_pandas()

You can also pass values for the start_date and end_date attributes in yyyy-MM-dd or yyyy-MM-dd hh:mm:ss format to filter the sampling period.

ts = td.time_series(
    symbol="AAPL",
    interval="1day",
    outputsize=5,
    start_date = "2020-10-01",
    end_date = "2020-12-31"
)

ts.as_pandas()

The time_series() method allows data retrieval in Pandas, JSON, CSV, and URL formats.

I recommend retrieving time series in a Pandas dataframe since it is easier to manipulate and plot. For all other endpoints, the JSON format works well.

 A previous section explained that the as_pandas() method of the time_series object returns data in Pandas format. Let’s see how to retrieve data in JSON, CSV, and URL formats.

JSON Format

The as_json() method from the time_series object returns data in JSON format.

ts.as_json()

CSV Format

You can retrieve data in CSV (comma-separated values) format using the as_csv() method.

ts.as_csv()

URL Format

The as_url() method returns API URLs that the twelvedata library uses behind the scenes while making API calls.

ts.as_url()

Batch Requests

You can retrieve time series data for multiple stocks by passing a list of stock symbols to the symbol attribute.

The as_json() method returns a dictionary with stock symbols as keys. You can retrieve data for a particular stock using the symbol value as the key to the response dictionary.

ts = td.time_series(
    symbol= ["AAPL", "MSFT", "TSLA"],
    interval="1day",
    outputsize=5,
    start_date = "2020-10-01",
    end_date = "2020-12-31"
)

response = ts.as_json()
response['MSFT']

The as_pandas() method returns a 3D dataframe with multiple indexes.

ts = td.time_series(
    symbol= ["AAPL", "MSFT", "TSLA"],
    interval="1day",
    outputsize=5,
    start_date = "2020-10-01",
    end_date = "2020-12-31"
)

response_df = ts.as_pandas()
response_df
response_df.loc['MSFT']

Exchange Rate

The exchange_rate() method returns the real-time exchange rates for currency pairs. You can retrieve both forex and currency pairs.

response = td.exchange_rate(symbol = "BTC/USD").as_json()
response

The exchange_rate() method returns the time stamp value in UNIX format, which you can convert to ISO format using the following script.

from datetime import datetime

t =  int(response['timestamp'])
print(datetime.fromtimestamp(t).isoformat())

Currency Conversion

The currency_conversion() method returns real-time exchange rates and the converted amount for currency pairs.

td.currency_conversion(symbol = "BTC/USD", amount = "5").as_json()

Quote

The quote() method returns the latest quote for an instrument.

td.quote(symbol = "AAPL").as_json()

Real-Time Price

The price() method returns a single-value real-time price for an instrument.

td.price(symbol = "AAPL").as_json()

End-of-Day Price

The eod() method returns a single-value end-of-day price for an instrument.

td.eod(symbol = "AAPL").as_json()

Fundamentals

The fundamental data endpoint returns financials, profiles, transactions, and other information for a broad range of US and international stocks.

Company Profile

The get_profile() method returns the company profile. The response contains core company information, along with a detailed description.

td.get_profile(symbol = "AAPL").as_json()

Company Statistics

The get_statistics() method returns company status such as price-to-earnings ratio, market capitalization, enterprise value, etc.

td.get_statistics(symbol = "AAPL").as_json()

Income Statement

The income_statement() method returns the income statement for a company.

td.get_income_statement(symbol = "AAPL").as_json()['income_statement']

Balance Sheet

You can retrieve the balance sheet for a company using the get_balance_sheet() method.

td.get_balance_sheet(symbol = "AAPL").as_json()

Cashflow

The cashflow() method returns a company’s cash flow.

td.get_cash_flow(symbol = "AAPL").as_json()

Fund Holders

The get_fund_holders() method returns information about a company’s stock owned by mutual fund holders.

td.get_fund_holders(symbol = "AAPL").as_json()
response  = td.get_fund_holders(symbol = "AAPL").as_json()
response_df = pd.DataFrame.from_records(response['fund_holders'])
response_df.head()

See the official documentation for other fundamental data endpoint methods.

Technical Indicators

The technical indicators endpoint methods return real-time and historical values for various technical indicators, such as BBands, SMA, EMA, etc., for an instrument. You can find the complete list of indicators in the official documentation.

The technical indicators endpoint is an extension of the time series endpoint. You first have to retrieve a time series using the time_series() method and then retrieve technical indicators for that time series using a with_{indicator_name}() method where indicator_name is the name of the indicator.

With OHLCV Values

By default, the with_{indicator_name}() method returns technical indicator values and OHLCV values.

For example, the script below returns SMA (simple moving average) values using the with_sma() method.

ts = td.time_series(
    symbol="AAPL",
    interval="1day",
    outputsize=100
)


response_df = ts.with_sma().as_pandas()
response_df.head()

Without OHLCV

If you do not want to retrieve the OHLCV values, you first need to call the without_ohlc() method and then call a with_{indicator_name}() method.

response_df = ts.without_ohlc().with_sma().as_pandas()
response_df.head()

Passing Parameters

You can pass parameter values (from the list of parameters) to a with_{indicator_name}() method. For instance, the following Python code returns SMA values with a time-period of 20.

response_df = ts.without_ohlc().with_sma(time_period = 20).as_pandas()
response_df.head()

Chaining Multiple Indicators

You can chain multiple indicators together. For instance, the following script returns Bollinger Bands, SMA with a time-period value of 20, and SMA with a time-period value of 40.

response_df = ts.without_ohlc().with_bbands(ma_type="EMA").with_sma(time_period = 20).with_sma(time_period = 40).as_pandas()
response_df.head()

Charts

The Charts endpoint methods allow you to plot static and interactive charts.

The official document doesn’t include Charts as one of the endpoints of the Twelve Data API. Their Python plugin lists Charts as an endpoint.

Static Charts

Static charts use the matplotlib library in the backend, requiring you to install the mplfinance package, which you can do with the following pip command.

pip install mplfinance

To plot a static chart, call the as_pyplot_figure() method on the time series object.

ts = td.time_series(
    symbol="AAPL",
    interval="1day",
    outputsize = 50

)
ts.as_pyplot_figure().show()

Interactive Charts

Interactive charts make use of the plotly library. You can plot an interactive chart using the as_plotly_figure().show() method.

ts.with_bbands(ma_type="EMA").\
with_sma(time_period = 20).\
with_sma(time_period = 40).as_plotly_figure()

WebSocket

The WebSocket endpoint allows you to retrieve real-time, streaming quote price data from the Twelve Data API.

I tried to retrieve streaming data via WebSockets using the Python twelvedata library (following the instructions in the documentation), but it returned an error.

td = TDClient(apikey = api_key)

messages_history = []

def on_event(e):
    # do whatever is needed with data
    print(e)
    messages_history.append(e)


ws = td.websocket(on_event=on_event)
ws.subscribe(["BTC/USD"])
ws.connect()
while True:
    print('messages received: ', len(messages_history))
    ws.heartbeat()
    time.sleep(10)

An alternative way to retrieve streaming data using WebSockets is via the Python requests module. The def on_message() in the following script executes every time you receive a data stream.

You can subscribe to a symbol using the subscription_request dictionary in the on_open() method. The following script retrieves streaming price information for “BTC/USD”.

For demo purposes, the WebSocket is closed after receiving six messages. You can keep it open for as long as you want.

import websocket

websocket_url = f"wss://ws.twelvedata.com/v1/quotes/price?apikey={api_key}"

counter = 0

def on_message(ws, message):
    global counter
    data = json.loads(message)

    print(data)
    counter += 1
    print(" ============== Total messages received ================", counter)

    if counter == 6:
        ws.close()

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("WebSocket closed")

# Define the on_open function to send the 
# subscription request once the WebSocket is open
def on_open(ws):
    # Define the subscription request
    subscription_request = {
        "action": "subscribe",
        "params": {
            "symbols": "BTC/USD"
        }
    }
    # Send the subscription request
    ws.send(json.dumps(subscription_request))

# Connect to the WebSocket

ws = websocket.WebSocketApp(websocket_url, 
                            on_message=on_message, 
                            on_error=on_error, 
                            on_close=on_close)
ws.on_open = on_open
ws.run_forever()

Analysis

The analysis endpoint contains methods returning analysts’ estimates and recommendations for a company’s future indicators, such as earnings estimate, earnings per share, price targets, etc.

The analysis endpoint is relatively newer, and the Python twelvedata library still needs to implement it. You can use the Python requests module to retrieve data from this endpoint.

Earnings Estimate

The /earnings_estimate endpoint URL returns the earnings estimate for a company.

base_url = 'https://api.twelvedata.com'
endpoint = '/earnings_estimate?'
symbol = 'AAPL'

query = 'apikey={}&symbol={}'.format(api_key, 
                                     symbol)

response = requests.get(base_url + endpoint + query)
response.json()

Recommendations

The /recommendations endpoint URL returns mean analyst recommendations for an instrument,  classified as Strong Buy, Buy, Hold, or Sell, along with a recommendation score.

base_url = 'https://api.twelvedata.com'
endpoint = '/recommendations?'
symbol = 'AAPL'

query = 'apikey={}&symbol={}'.format(api_key, 
                                     symbol)

response = requests.get(base_url + endpoint + query)
response.json()

Mutual Funds

The mutual funds endpoint returns information such as mutual funds list, type, summary, etc.

Mutual Funds List

The /mutual_funds/list endpoint URL returns a list of all mutual funds available with Twelve Data.

base_url = 'https://api.twelvedata.com'
endpoint = '/mutual_funds/list?'

query = 'apikey={}'.format(api_key)

response = requests.get(base_url + endpoint + query)
response.json()

Mutual Funds Type

The /mutual_funds/type endpoint URL returns a list of all mutual fund types available with Twelve Data.

base_url = 'https://api.twelvedata.com'
endpoint = '/mutual_funds/type?'

query = 'apikey={}'.format(api_key)

response = requests.get(base_url + endpoint + query)
response.json()

Twelve Data Plugins

In addition to Python, Twelve Data officially supports the following plugins:

Following are some third-party packages for Twelve Data:

Twelve Data Alternatives

Following are some alternatives to Twelve Data:

The Bottom Line

The Twelve Data API is a game-changer for traders and analysts seeking automation and data insights. Our tutorial has equipped you to navigate Python endpoints, tap into historical and real-time market data, utilize technical indicators, and comprehend exchange rates.

With the Python twelvedata library and the requests module, you’re now poised to make sharp trading decisions. So, get started with Twelve Data API today and skyrocket your trading prowess!

Leave a Comment