Twelve Data Python Client

repository·master·Indexed 18 days ago

https://github.com/twelvedata/twelvedata-python

Official Python library for the Twelve Data financial API and WebSocket service. It provides access to time series data (stocks, forex, crypto, ETFs, indices), fundamental data, and over 100 technical indicators. Features include support for pandas DataFrames, static and interactive charting via matplotlib and plotly, real-time data streaming via WebSockets, and batch requests for up to 120 symbols.

Tokens
19.4K
Snippets
101
Records
130
Agent score
73%

What's inside twelvedata-python

  1. Overview of Twelve Data Python Client features

    master

    The Twelve Data Python client provides access to the Twelve Data financial API and WebSocket services. Key capabilities include:

    • Time Series Data: Retrieve OHLC (Open, High, Low, Close) data for stocks, forex, cryptocurrency, ETFs, and indices.
    • Fundamental Data: Access company profiles, financials, and other fundamental metrics.
    • Technical Indicators: Access over 100+ technical indicators.
    • Flexible Output Formats: Data can be returned in json, csv, or pandas formats.
    • Charting: Full support for both static and dynamic charts.
    • Real-time Data: Real-time data streaming via WebSockets.

    Note: An API key is required to use the service.

  2. How technical indicators work with Time Series

    master

    Technical indicators are applied to a time_series() object using a fluent interface. You can chain multiple indicators together using the .with_{IndicatorName} pattern.

    Key behaviors:

    • Chaining: Indicators can be used in arbitrary order and conjugated (e.g., .with_ema().with_macd()).
    • Parameters: Each indicator accepts specific parameters (e.g., .with_bbands(ma_type="EMA")). If not provided, defaults are used.
    • OHLC Control: By default, indicators include OHLC values. Use .without_ohlc() to remove them from the output.
    • Output Formats: Indicators support .as_pandas() and .as_json().
    from twelvedata import TDClient
    
    td = TDClient(apikey="YOUR_API_KEY_HERE")
    ts = td.time_series(
        symbol="ETH/BTC",
        exchange="Huobi",
        interval="5min",
        outputsize=22,
        timezone="America/New_York",
    )
    
    # Returns: OHLC, BBANDS(close, 20, 2, EMA), PLUS_DI(9), WMA(20), WMA(40)
    ts.with_bbands(ma_type="EMA").with_plus_di().with_wma(time_period=20).with_wma(time_period=40).as_pandas()
    
    # Returns: STOCH(14, 1, 3, SMA, SMA), TSF(close, 9) without OHLC
    ts.without_ohlc().with_stoch().with_tsf().as_json()
  3. Generate Static and Interactive Charts

    master

    The library supports two types of charting:

    1. Static Charts: Based on matplotlib. Requires the mplfinance package. Use .as_pyplot_figure().
    2. Interactive Charts: Based on plotly. Use .as_plotly_figure().show().

    Both methods can be used on a standard time series or a time series with technical indicators applied.

    # Static Chart (requires mplfinance)
    ts.as_pyplot_figure()
    
    # Interactive Chart (requires plotly)
    ts.with_ema(time_period=7).with_macd().as_plotly_figure().show()
  4. Use WebSockets for real-time data

    master

    WebSockets provide a low-latency, duplex communication channel for real-time financial quotes. This feature requires a Pro plan or higher and the websocket_client package.

    Workflow:

    1. Initialize td.websocket(symbols=..., on_event=...).
    2. The on_event callback function handles incoming data.
    3. Call .connect() to start the stream.
    4. Use .heartbeat() periodically to maintain the connection.
    5. Use .subscribe() or .unsubscribe() to manage active symbols.

    Methods:

    • ws.subscribe([list]): Subscribe to symbols.
    • ws.unsubscribe([list]): Stop receiving data for symbols.
    • ws.reset(): Unsubscribe from all symbols.
    • ws.connect(): Establish connection.
    • ws.disconnect(): Close connection.
    • ws.heartbeat(): Send heartbeat to server.
    import time
    from twelvedata import TDClient
    
    def on_event(e):
        print(e)
    
    td = TDClient(apikey="YOUR_API_KEY_HERE")
    ws = td.websocket(symbols="BTC/USD", on_event=on_event)
    ws.subscribe(['ETH/BTC', 'AAPL'])
    ws.connect()
    
    while True:
        ws.heartbeat()
        time.sleep(10)
  5. Install the Twelve Data Python client

    master

    You can install the twelvedata library using pip. Depending on your needs, you can install the base package or include optional dependencies for data analysis and real-time streaming.

    • Base installation: Minimal package without optional dependencies.
    • With pandas support: Adds support for returning data as pandas.DataFrame objects.
    • Full installation: Includes pandas, matplotlib, plotly, and websocket-client for advanced charting and real-time WebSocket data streams.
    # Base installation
    pip install twelvedata
    
    # Install with pandas support
    pip install twelvedata[pandas]
    
    # Full installation with pandas, matplotlib, plotly, and websocket support
    pip install twelvedata[pandas,matplotlib,plotly,websocket-client]
  6. Initialize the TDClient

    master

    The TDClient is the primary entry point for the Twelve Data Python library. It requires an apikey parameter to authenticate your requests. All core data, fundamentals, and technical indicator methods are accessed through an instance of this class.

    from twelvedata import TDClient
    
    # Initialize client - apikey parameter is required
    td = TDClient(apikey="YOUR_API_KEY_HERE")
  7. Configure API credentials and settings with Context

    master

    The Context class is used by all request builders to manage session settings and authentication. It holds the apikey required for Twelvedata API access, the base_url, the http_client, and a defaults dictionary for parameters used across requests. It also manages self_heal_time_s, which defines the retry interval in seconds.

    You can create a new context or derive one from an existing one using from_context(ctx) to ensure consistent settings across different parts of your application.

    # Example of how Context attributes are structured
    # Note: Actual instantiation typically happens via the main client
    ctx = Context()
    ctx.apikey = 'YOUR_API_KEY'
    ctx.base_url = 'https://api.twelvedata.com'
    ctx.defaults = {'format': 'json'}
    ctx.self_heal_time_s = 5
  8. How TDClient request builders work

    master
    Most methods in TDClient do not return data directly. Instead, they return a request builder instance (an endpoint object). You use these builders to specify parameters for your specific query. The client uses a Context object to manage shared state like the API key, base URL, and default parameters across these builders.
  9. Handle incoming WebSocket events with on_event

    master

    When using TDWebSocket, you can process incoming real-time data by providing a callback function to the on_event parameter in your configuration/context.

    The TDWebSocket uses an internal EventHandler thread that continuously pulls events from a queue and passes them to your provided function. If no function is provided, events are simply queued and discarded by the handler.

    To ensure your application can keep up with the data stream, monitor for the error message: "Event queue is full. New events are not added." which indicates your on_event handler is too slow or the max_queue_size is too small.

    def my_event_handler(data):
        print(f"Received data: {data}")
    
    # The handler is typically passed via the context/defaults used to initialize TDWebSocket
    # ctx.defaults = {'on_event': my_event_handler}
  10. Debug API requests with .as_url()

    master

    If a method is not returning the expected data or is throwing errors, you can inspect the actual HTTP request being sent. Append .as_url() to any method or chain of methods to return a list of the URLs used to construct the request.

    ts = td.time_series(symbol="AAPL", interval="1min").with_bbands().with_ema()
    print(ts.as_url())
  11. Retrieve Time Series data

    master

    Use TDClient.time_series() to fetch historical market data. You can specify parameters like symbol, interval, outputsize, and timezone.

    Once a time series object is created, you can convert the output into different formats:

    • ts.as_json(): Returns a JSON array.
    • ts.as_csv(): Returns CSV data with a header.
    • ts.as_pandas(): Returns a pandas.DataFrame.
    • ts.as_url(): Returns a list of the URLs used to construct the request.
    from twelvedata import TDClient
    
    td = TDClient(apikey="YOUR_API_KEY_HERE")
    
    # Construct the necessary time series
    ts = td.time_series(
        symbol="AAPL",
        interval="1min",
        outputsize=10,
        timezone="America/New_York",
    )
    
    # Returns pandas.DataFrame
    df = ts.as_pandas()
  12. Perform Batch Requests for multiple symbols

    master

    You can request data for up to 120 symbols in a single API call. This is supported by passing a comma-delimited string or a list of symbols to the symbol parameter.

    Important: Batch requests are only supported with .as_json() and .as_pandas() formats.

    • .as_json() returns a dictionary where keys are the symbols and values are the data tuples.
    • .as_pandas() returns a 3D DataFrame with a MultiIndex of (symbol, datetime).
    # Option 1: Comma-delimited string
    ts = td.time_series(symbol="V, RY, AUD/CAD, BTC/USD", interval="1day")
    
    # Option 2: List of symbols
    ts = td.time_series(symbol=["V", "RY", "AUD/CAD", "BTC/USD"], interval="1day")
    
    # Using as_pandas with batch
    df = ts.with_macd().as_pandas()
    # Access specific symbol via MultiIndex: df.loc['AAPL']