twelvedata
twelvedata-python
Python

Twelve Data Python Client - Financial data API & WebSocket

Last updated Jul 3, 2026
752
Stars
111
Forks
0
Issues
+4
Stars/day
Attention Score
94
Language breakdown
Python 100.0%
Files click to expand
README

Build Status Open Issues Latest Stable Version License

Twelve Data Python Client for financial API & WebSocket

Official python library for Twelve Data. This package supports all main features of the service:

  • Get stock, forex, cryptocurrency, ETF, and index OHLC time series.
  • Companies' profiles, financials, and much more fundamentals data.
  • Get over 100+ technical indicators.
  • Output data as: json, csv, pandas
  • Full support for static and dynamic charts.
  • Real-time WebSocket data stream.
API key is required. If you don't have it yet, get it by signing up here.

Installation

Use the package manager pip to install Twelve Data API library (without optional dependencies):

pip install twelvedata

Or install with pandas support:

pip install twelvedata[pandas]

Or install with pandas, matplotlib, plotly, and websocket support:

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

Usage

Supported parameters

| Parameter | Description | Type | Required | | ---------- | :----------------------------------------------------------- | ------ | -------- | | symbol | stock ticker (e.g. AAPL, MSFT);
physical currency pair (e.g. EUR/USD, CNY/JPY);
digital currency pair (BTC/USD, XRP/ETH) | string | yes | | interval | time frame: 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month | string | yes | | apikey | your personal API Key, if you don't have one - get it here | string | yes | | exchange | if symbol is traded in multiple exchanges specify the desired one, valid for both stocks and cryptocurrencies | string | no | | mic_code | Market Identifier Code (MIC) under ISO 10383 standard, valid for stocks | string | no | | country | if symbol is traded in multiple countries specify the desired one, valid for stocks | string | no | | outputsize | number of data points to retrieve | int | no | | timezone | timezone at which output datetime will be displayed, supports: UTC, Exchange or according to IANA Time Zone Database | string | no | | start_date | start date and time of sampling period, accepts yyyy-MM-dd or yyyy-MM-dd hh:mm:ss format | string | no | | end_date | end date and time of sampling period, accepts yyyy-MM-dd or yyyy-MM-dd hh:mm:ss format | string | no | | order | sorting order of the time series output, supports desc or asc | string | no | | date | Could be the exact date, e.g. 2021-10-27, or in human language today or yesterday | string | no |

The basis for all methods is the TDClient object that takes the required apikey parameter.

Time series

  • TDClient.time_series() accepts all common parameters. Time series may be converted to several formats:
* ts.as_json() - will return JSON array * ts.as_csv() - will return CSV with header * ts.as_pandas() - will return pandas.DataFrame * ts.as_url() - will return list of URLs used
from twelvedata import TDClient

Initialize client - apikey parameter is requiered

td = TDClient(apikey="YOURAPIKEY_HERE")

Construct the necessary time series

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

Returns pandas.DataFrame

ts.as_pandas()

Other core data endpoints:

  • Exchange rate - TDClient.exchange_rate(symbol)
  • Currency conversion - TDClient.currency_conversion(symbol, amount)
  • Quote - TDClient.quote() takes parameters as .time_series()
  • Real-time price - TDClient.price() takes parameters as .time_series()
  • End of day price - TDClient.eod() takes parameters as .time_series()

Fundamentals

All fundamentals are supported across global markets. Refer to API documentation here and find out which countries support which fundamentals by visiting this page.

  • .get_logo(symbol, exchange, country, type)
  • .get_profile(symbol, exchange, country, type)
  • .get_dividends(symbol, exchange, country, type)
  • .get_splits(symbol, exchange, country, type)
  • .getearnings(symbol, exchange, country, type, period, outputsize, startdate, end_date)
  • .getearningscalendar(symbol, exchange, country, period, startdate, enddate)
  • .getipocalendar(symbol, exchange, country, startdate, enddate)
  • .get_statistics(symbol, exchange, country, type)
  • .getinsidertransactions(symbol, exchange, country, type)
  • .getincomestatement(symbol, exchange, country, type, period, startdate, enddate)
  • .getbalancesheet(symbol, exchange, country, type, period, startdate, enddate)
  • .getcashflow(symbol, exchange, country, type, period, startdate, enddate)
  • .getkeyexecutives(symbol, exchange, country, type)
  • .getinstitutionalholders(symbol, exchange, country, type)
  • .getfundholders(symbol, exchange, country, type)
Only JSON format is supported accessible via .as_json()
from twelvedata import TDClient

td = TDClient(apikey="YOURAPIKEY_HERE")

Get last dividends for AAPL

dividends = td.get_dividends( symbol="AAPL", ).as_json()

Technical indicators

This Python library supports all indicators implemented by Twelve Data. Full list of 100+ technical indicators may be found in API documentation.

  • Technical indicators are part of TDClient.time_series() object.
  • It shares the universal format TDClient.timeseries().with{Technical Indicator Name}, e.g. .withbbands(), .withpercentb(), .withmacd()
  • Indicator object accepts all parameters according to its specification in API documentation, e.g. .withbbands() accepts: seriestype, timeperiod, sd, ma_type. If parameter is not provided it will be set to default value.
  • Indicators may be used in arbitrary order and conjugated, e.g. TDClient.timeseries().witharoon().withadx().withema()
  • By default, technical indicator will output with OHLC values. If you do not need OHLC, specify TDClient.timeseries().withoutohlc()
from twelvedata import TDClient

td = TDClient(apikey="YOURAPIKEY_HERE") ts = td.time_series( symbol="ETH/BTC", exchange="Huobi", interval="5min", outputsize=22, timez, )

Returns: OHLC, BBANDS(close, 20, 2, EMA), PLUS_DI(9), WMA(20), WMA(40)

ts.withbbands(matype="EMA").withplusdi().withwma(timeperiod=20).withwma(timeperiod=40).as_pandas()

Returns: STOCH(14, 1, 3, SMA, SMA), TSF(close, 9)

ts.withoutohlc().withstoch().withtsf().asjson()

Batch requests

With batch requests up to 120 symbols might be returned per single API call. There are two options on how to do this:

# 1. Pass instruments symbols as a string delimited by comma (,)
ts = td.time_series(
    symbol="V, RY, AUD/CAD, BTC/USD",
    interval="1day",
)

2. Pass as a list of symbols

ts = td.time_series( symbol=["V", "RY", "AUD/CAD", "BTC/USD"], interval="1day", )

Important. Batch requests are only supported with .asjson() and .aspandas() formats.

With .as_json() the output will be a dictionary with passed symbols as keys. The value will be a tuple with quotes, just the same as with a single request.

ts = td.time_series(symbol='AAPL,MSFT', interval="1min", outputsize=3) df = ts.withmacd().withmacd(fastperiod=10).withstoch().as_json()

{ "AAPL": ({'datetime': '2020-04-23 15:59:00', 'open': '275.23001', 'high': '275.25000', 'low': '274.92999', 'close': '275.01001', 'volume': '393317', 'macd1': '-0.33538', 'macdsignal1': '-0.24294', 'macdhist1': '-0.09244', 'macd2': '-0.40894', 'macdsignal2': '-0.29719', 'macdhist2': '-0.11175', 'slowk': '4.52069', 'slowd': '7.92871'}, {'datetime': '2020-04-23 15:58:00', 'open': '275.07001', 'high': '275.26999', 'low': '275.00000', 'close': '275.25000', 'volume': '177685', 'macd1': '-0.31486', 'macdsignal1': '-0.21983', 'macdhist1': '-0.09503', 'macd2': '-0.38598', 'macdsignal2': '-0.26925', 'macdhist2': '-0.11672', 'slowk': '14.70578', 'slowd': '6.82079'}, {'datetime': '2020-04-23 15:57:00', 'open': '275.07001', 'high': '275.16000', 'low': '275.00000', 'close': '275.07751', 'volume': '151169', 'macd1': '-0.30852', 'macdsignal1': '-0.19607', 'macdhist1': '-0.11245', 'macd2': '-0.38293', 'macdsignal2': '-0.24007', 'macdhist2': '-0.14286', 'slowk': '4.55965', 'slowd': '2.75237'}), "MSFT": ({'datetime': '2020-04-23 15:59:00', 'open': '171.59000', 'high': '171.64000', 'low': '171.22000', 'close': '171.42000', 'volume': '477631', 'macd1': '-0.12756', 'macdsignal1': '-0.10878', 'macdhist1': '-0.01878', 'macd2': '-0.15109', 'macdsignal2': '-0.12915', 'macdhist2': '-0.02193', 'slowk': '20.95244', 'slowd': '26.34919'}, {'datetime': '2020-04-23 15:58:00', 'open': '171.41000', 'high': '171.61000', 'low': '171.33501', 'close': '171.61000', 'volume': '209594', 'macd1': '-0.12440', 'macdsignal1': '-0.10408', 'macdhist1': '-0.02032', 'macd2': '-0.14786', 'macdsignal2': '-0.12367', 'macdhist2': '-0.02419', 'slowk': '39.04785', 'slowd': '23.80945'}, {'datetime': '2020-04-23 15:57:00', 'open': '171.34500', 'high': '171.48000', 'low': '171.25999', 'close': '171.39999', 'volume': '142450', 'macd1': '-0.13791', 'macdsignal1': '-0.09900', 'macdhist1': '-0.03891', 'macd2': '-0.16800', 'macdsignal2': '-0.11762', 'macdhist2': '-0.05037', 'slowk': '19.04727', 'slowd': '14.92063'}) }

With .as_pandas() the output will be a 3D DataFrame with MultiIndex for (symbol, datetime).

ts = td.time_series(symbol='AAPL,MSFT', interval="1min", outputsize=3) df = ts.withmacd().withmacd(fastperiod=10).withstoch().as_pandas()

open high ... slowk slowd

AAPL 2020-04-23 15:59:00 275.23001 275.25000 ... 4.52069 7.92871

2020-04-23 15:58:00 275.07001 275.26999 ... 14.70578 6.82079

2020-04-23 15:57:00 275.07001 275.16000 ... 4.55965 2.75237

MSFT 2020-04-23 15:59:00 171.59000 171.64000 ... 20.95244 26.34919

2020-04-23 15:58:00 171.41000 171.61000 ... 39.04785 23.80945

2020-04-23 15:57:00 171.34500 171.48000 ... 19.04727 14.92063

#

[6 rows x 13 columns]

df.loc['AAPL']

open high ... slowk slowd

2020-04-23 15:59:00 275.23001 275.25000 ... 4.52069 7.92871

2020-04-23 15:58:00 275.07001 275.26999 ... 14.70578 6.82079

2020-04-23 15:57:00 275.07001 275.16000 ... 4.55965 2.75237

#

[3 rows x 13 columns]

df.columns

Index(['open', 'high', 'low', 'close', 'volume', 'macd1', 'macd_signal1',

'macdhist1', 'macd2', 'macdsignal2', 'macdhist2', 'slowk',

'slow_d'],

dtype='object')

Charts

Charts support OHLC, technical indicators and custom bars.

Static

Static charts are based on matplotlib library and require mplfinance package to be installed.

static chart example

  • Use .aspyplotfigure()
from twelvedata import TDClient

td = TDClient(apikey="YOURAPIKEY_HERE") ts = td.time_series( symbol="MSFT", outputsize=75, interval="1day", )

1. Returns OHLCV chart

ts.aspyplotfigure()

2. Returns OHLCV + BBANDS(close, 20, 2, SMA) + %B(close, 20, 2 SMA) + STOCH(14, 3, 3, SMA, SMA)

ts.withbbands().withpercentb().withstoch(slowkperiod=3).aspyplotfigure()

Interactive

Interactive charts are built on top of plotly library.

interactive chart example

  • Use .asplotlyfigure().show()
from twelvedata import TDClient

td = TDClient(apikey="YOURAPIKEY_HERE") ts = td.time_series( symbol="DNR", outputsize=50, interval="1week", )

1. Returns OHLCV chart

ts.asplotlyfigure()

2. Returns OHLCV + EMA(close, 7) + MAMA(close, 0.5, 0.05) + MOM(close, 9) + MACD(close, 12, 26, 9)

ts.withema(timeperiod=7).withmama().withmom().withmacd().asplotly_figure().show()

WebSocket

With the WebSocket, a duplex communication channel with the server is established.

Make sure to have websocketclient package installed.

websocket example

Features

  • Real-time low latency stream of financial quotes.
  • You might subscribe to stocks, forex, and crypto.

Example

import time
from twelvedata import TDClient

messages_history = []

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

td = TDClient(apikey="YOURAPIKEY_HERE") ws = td.websocket(symbols="BTC/USD", onevent=onevent) ws.subscribe(['ETH/BTC', 'AAPL']) ws.connect() while True: print('messages received: ', len(messages_history)) ws.heartbeat() time.sleep(10)

Parameters accepted by the .websocket() object:

  • symbols list of symbols to subscribe
  • on_event function that invokes when event from server is received
  • logger instance of logger, otherwise set to default
  • maxqueuesize maximum size of queue, default 12000
  • log_level accepts debug or info, otherwise not set
Applicable methods on .websocket() object:
  • ws.subscribe([list of symbols]): get data from the symbols passed
  • ws.unsubscribe([list of symbols]): stop receiving data from the symbols passed
  • ws.reset(): unsubscribe from all symbols
  • ws.connect(): establish connection with WebSocket server
  • ws.disconnect(): close connection with WebSocket server
  • ws.heartbeat(): send heartbeat to server
Important. Do not forget that WebSockets are only available for Twelve Data users on the Pro plan and above. Checkout the trial here.

Advanced

Custom endpoint

This method is used to request unrepresented endpoints on this package, but which are available at Twelve Data.
endpoint = td.custom_endpoint(
    name="quote",
    symbol="AAPL",
)
endpoint.as_json()

The only required parameter is name which should be identical to the endpoint used at Twelve Data. All others can be custom and will vary according to the method.

Debugging

When the method doesn't return the desired data or throws an error, it might be helpful to understand and analyze the API query behind it. Add .as_url() to any method or chain of methods, and it will return the list of used URLs.
ts = td.time_series(
    symbol="AAPL",
    interval="1min",
    outputsize=10,
    timez,
).withbbands().withema()

ts.as_url()

['https://api.twelvedata.com/timeseries?symbol=AAPL&interval=1min&outputsize=10&dp=5&timezone=America/NewYork&order=desc&prepost=false&format=JSON&apikey=demo',

'https://api.twelvedata.com/bbands?symbol=AAPL&interval=1min&seriestype=close&timeperiod=20&sd=2&matype=SMA&outputsize=10&dp=5&timezone=America/NewYork&order=desc&prepost=false&format=JSON&apikey=demo',

'https://api.twelvedata.com/ema?symbol=AAPL&interval=1min&seriestype=close&timeperiod=9&outputsize=10&dp=5&timezone=America/New_York&order=desc&prepost=false&format=JSON&apikey=demo']

API usage

This method gives an overview of the current API credits consumption.
api = td.api_usage()

Support

Visit our official website contact page or support center.

Announcements

Follow us for announcements and updates about this library.

Roadmap

  • [x] Fundamentals
  • [x] WebSocket
  • [x] Batch requests
  • [x] Custom plots coloring
  • [x] Interactive charts (plotly)
  • [x] Static charts (matplotlib)
  • [x] Pandas support

Contributing

  • Clone repo and create a new branch: $ git checkout https://github.com/twelvedata/twelvedata -b namefornew_branch.
  • Make changes and test.
  • Submit Pull Request with comprehensive description of changes.

License

This package is open-sourced software licensed under the MIT license.

🔗 More in this category

© 2026 GitRepoTrend · twelvedata/twelvedata-python · Updated daily from GitHub