Nasdaq Data Link Python Client

repository·main·Indexed 18 days ago

https://github.com/nasdaq/data-link-python

Official SDK for the Nasdaq Data Link RESTful API, enabling developers to programmatically retrieve time-series and datatable data into pandas DataFrames. The library supports dataset retrieval via nasdaqdatalink.get(), datatable queries with pagination via nasdaqdatalink.get_table(), point-in-time data retrieval, and bulk downloads of entire databases as ZIP files. Compatible with Python v3.7+.

Tokens
4.7K
Snippets
18
Records
22
Agent score
71%

What's inside nasdaq-data-link-python

  1. Handle paginated lists and metadata

    main

    Methods like Database.all() and Dataset.all() return a PaginatedList (or ModelList). These objects allow you to check for more results using has_more_results() and access request metadata like current_page or total_results via hash lookup or convenience methods. Note that iterating through a list only iterates through the current page; you must fetch subsequent pages manually using params={'page': N}.

    import nasdaqdatalink
    
    # Get first page of databases
    databases = nasdaqdatalink.Database.all()
    
    # Check for more results and access metadata
    if databases.has_more_results():
        print(f"Page: {databases.current_page}")
        
        # Fetch the next page
        more_databases = nasdaqdatalink.Database.all(params={'page': 2})
        for db in more_databases:
            print(db.database_code)
    
    # Access raw values or metadata
    print(databases.values)
    print(databases.meta)
  2. Retrieve data using the Quick method

    main

    The Quick method is used for simple data retrieval. Both methods return data as a pandas DataFrame.

    Retrieve Time-Series (Dataset) Data

    Use nasdaqdatalink.get() to retrieve dataset data:

    import nasdaqdatalink
    data = nasdaqdatalink.get('NSE/OIL')
    # data is a pandas DataFrame

    Retrieve Non-Time Series (Datatable) Data

    Use nasdaqdatalink.get_table() to retrieve datatable data:

    import nasdaqdatalink
    data = nasdaqdatalink.get_table('ZACKS/FC', ticker='AAPL')
    # data is a pandas DataFrame

    Note: If an api_key is not set, you may receive limited or sample data.

    import nasdaqdatalink
    data = nasdaqdatalink.get('NSE/OIL')
  3. Enable debug logging

    main

    To enable debug logs for the nasdaqdatalink module, use the standard Python logging library:

    import nasdaqdatalink
    import logging
    
    logging.basicConfig()
    
    data_link_log = logging.getLogger("nasdaqdatalink")
    data_link_log.setLevel(logging.DEBUG)
  4. Configure the nasdaq-data-link client

    main

    The client can be configured via code, environment variables, or a local API key file.

    Configuration Options

    OptionExplanationExample
    api_keyYour access key used to identify yourself and provide full access.tEsTkEy123456789
    use_retriesWhether API calls which return statuses in retry_status_codes should be automatically retried.True
    number_of_retriesMaximum number of retries that should be attempted. Only used if use_retries is True.5
    max_wait_between_retriesMaximum amount of time in seconds that should be waited before attempting a retry. Only used if use_retries is True.8
    retry_backoff_factorDetermines the amount of time in seconds that should be waited before attempting another retry. This factor is exponential (e.g., 0.5 results in waits of [0.5, 1, 2, 4, etc]). Only used if use_retries is True.0.5
    retry_status_codesA list of HTTP status codes which will trigger a retry. Only used if use_retries is True.[429, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511]

    SSL Verification

    By default, SSL verification is enabled. To bypass it (not recommended):

    nasdaqdatalink.ApiConfig.verify_ssl = False
  5. Configure via Local API Key File

    main

    The client automatically attempts to load an API key from ~/.nasdaq/data_link_apikey if it exists.

    Note: If the file exists but is empty, a ValueError will be thrown.

    If you want to use a custom path for your API key file, call read_key() explicitly:

    import nasdaqdatalink
    nasdaqdatalink.read_key(filename="/data/.corporatenasdaqdatalinkapikey")
  6. Configure via Environment Variables

    main

    You can use environment variables to configure the SDK without inline boilerplate:

    EnvDescription
    NASDAQ_DATA_LINK_API_KEYThe SDK will configure itself to use the given API Key. This takes precedence over the local API key file.
    NASDAQ_DATA_LINK_BASE_DOMAINThe SDK will configure itself to use the provided domain.
  7. Merge multiple datasets into a MergedDataset

    main

    A MergedDataset allows you to perform a full outer join on multiple datasets. You can specify specific columns to include from each dataset using the column_index key in a configuration dictionary.

    import nasdaqdatalink
    
    # Merge specific columns from AAPL and MSFT with all columns from TWTR
    merged_dataset = nasdaqdatalink.MergedDataset([
        ('WIKI/AAPL', {'column_index': [11]}),
        ('WIKI/MSFT', {'column_index': [9, 11]}), 
        'WIKI/TWTR'
    ])
    
    # Retrieve the merged data
    data = merged_dataset.data()
  8. Bulk download an entire Database

    main

    To download all datasets within a database, use the Database object. You can either retrieve a download URL or download the files directly to a local path. Use the params argument to specify the download_type (e.g., 'partial' or 'complete').

    import nasdaqdatalink
    
    # Get the download URL
    url = nasdaqdatalink.Database('ZEA').bulk_download_url()
    
    # Download to a local folder or file
    nasdaqdatalink.Database('ZEA').bulk_download_to_file('/path/to/destination')
    
    # Perform a partial bulk download
    nasdaqdatalink.Database('ZEA').bulk_download_to_file('.', params={'download_type': 'partial'})
  9. Retrieve point-in-time data with nasdaqdatalink.get_point_in_time()

    main

    Use nasdaqdatalink.get_point_in_time() to retrieve data based on specific date intervals. Dates must be provided as valid ISO8601 formatted strings (e.g., 2021-03-02 or 2021-03-02T13:45:00).

    Available Intervals

    IntervalDescriptionRequired ParametersExample
    asofdateReturns data as of a specific datedateget_point_in_time('DB/CODE', interval='asofdate', date='2020-01-01')
    fromReturns data from start up to but excluding endstart_date, end_dateget_point_in_time('DB/CODE', interval='from', start_date='2020-01-01', end_date='2020-02-01')
    betweenReturns data inclusively between datesstart_date, end_dateget_point_in_time('DB/CODE', interval='between', start_date='2020-01-01', end_date='2020-01-31')

    Usage Example

    import nasdaqdatalink
    data = nasdaqdatalink.get_point_in_time('DATABASE/CODE', interval='asofdate', date='2020-01-01')
    import nasdaqdatalink
    data = nasdaqdatalink.get_point_in_time('DATABASE/CODE', interval='asofdate', date='2020-01-01')
  10. Query data from a Datatable with pagination

    main

    Datatables can be queried using Datatable.data(). Unlike datasets, datatables may be paginated. If the returned data contains a cursor_id in its metadata, you must make subsequent calls by passing that cursor_id within the qopts dictionary inside the params argument to retrieve the next page.

    # Initial call
    data = nasdaqdatalink.Datatable('ZACKS/FC').data()
    
    # Subsequent call using cursor_id from metadata
    data2 = nasdaqdatalink.Datatable('ZACKS/FC').data(params={'qopts': {'cursor_id': data.meta['next_cursor_id']}})
    
    # Pattern for iterating through all pages
    data_list = []
    cursor_id = None
    while True:
        data = nasdaqdatalink.Datatable('ZACKS/FC').data(params={
            'ticker': ['AAPL', 'MSFT'], 
            'per_end_date': {'gte': '2015-01-01'}, 
            'qopts': {'columns': ['ticker', 'comp_name'], 'cursor_id': cursor_id}
        })
        cursor_id = data.meta['next_cursor_id']
        data_list.append(data)
        if cursor_id is None:
            break
  11. Bulk download entire databases with nasdaqdatalink.bulkdownload()

    main

    Use nasdaqdatalink.bulkdownload() to download an entire database as a zip file to your current working directory. The method returns the filename of the downloaded zip.

    Basic Bulk Download

    import nasdaqdatalink
    asdaqdatalink.bulkdownload('EOD')

    Partial Download

    To download only the data from the previous day, use download_type='partial':

    import nasdaqdatalink
    asdaqdatalink.bulkdownload('EOD', download_type='partial')

    Custom Filename

    Specify a custom path and filename using the filename option:

    import nasdaqdatalink
    asdaqdatalink.bulkdownload('EOD', filename='/my/path/EOD_DB.zip')
    import nasdaqdatalink
    asdaqdatalink.bulkdownload('EOD')