# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['coinmetrics']

package_data = \
{'': ['*']}

install_requires = \
['orjson>=3.6.0,<4.0.0',
 'python-dateutil>=2.8.2,<3.0.0',
 'requests>=2.24.0,<3.0.0',
 'typer>=0.6.1,<0.7.0',
 'websocket-client>=1.2.1,<2.0.0']

extras_require = \
{'pandas': ['pandas>=1.3.3,<2.0.0']}

entry_points = \
{'console_scripts': ['coinmetrics = coinmetrics.typer_cli:main']}

setup_kwargs = {
    'name': 'coinmetrics-api-client',
    'version': '2023.2.27.22',
    'description': 'Python client for Coin Metrics API v4.',
    'long_description': '# Coin Metrics Python API v4 client library\n\nThis is an official Python API client for Coin Metrics API v4.\n\n## Installation and Updates\nTo install the client you can run the following command:\n```\npip install coinmetrics-api-client\n```\n\nNote that the client is updated regularly to reflect the changes made in [API v4](https://docs.coinmetrics.io/api/v4). Ensure that your latest version matches with what\'s in [pyPI](https://pypi.org/project/coinmetrics-api-client/) \n\nTo update your version, run the following command:\n```\npip install coinmetrics-api-client -U\n```\n\n## Introduction\nYou can use this client for querying all kinds of data with your API.\n\nTo initialize the client you should use your API key, and the CoinMetricsClient class like the following.\n```\nfrom coinmetrics.api_client import CoinMetricsClient\n\nclient = CoinMetricsClient("<cm_api_key>")\n\n# or to use community API:\nclient = CoinMetricsClient()\n```\n\nAfter that you can use the client object for getting information such as available markets:\n```\nprint(client.catalog_markets())\n```\n\nor to query all available assets along with what is available for those assets, like metrics, markets:\n\n```\nprint(client.catalog_assets())\n```\n\n\nyou can also use filters for the catalog endpoints like this:\n\n```\nprint(client.catalog_assets(assets=[\'btc\']))\n```\nin this case you would get all the information for btc only. \n\nYou can use this client to connect to our API v4 and get catalog or timeseries data from python environment. It natively supports paging over the data so you can use it to iterate over timeseries entries seamlessly.\n\nThe client can be used to query both pro and community data.\n\nThe full list of methods can be found in the [API Client Spec](https://coinmetrics.github.io/api-client-python/site/api_client.html).\n\n\nIf you\'d like a more wholistic view of what is offered from an API endpoint you can use the `to_dataframe()` function \nassociated with our catalog endpoints. The code snippet below shows getting a dataframe of information on all the \nassets that data is provided for:\n```python\nprint(client.catalog_assets().to_dataframe())\n```\n\nOutput:\n```commandline\n      asset          full_name          exchanges  ... metrics atlas  experimental\n0      100x           100xCoin          [gate.io]  ...     NaN  <NA>          <NA>\n1     10set             Tenset   [gate.io, lbank]  ...     NaN  <NA>          <NA>\n2       18c           Block 18            [huobi]  ...     NaN  <NA>          <NA>\n3      1art          ArtWallet          [gate.io]  ...     NaN  <NA>          <NA>\n4      1box               1BOX           [zb.com]  ...     NaN  <NA>          <NA>\n```\n\nNow you can use the pandas Dataframe functionality to do useful transformations, such as filtering out the assets \nwithout metrics available, then saving that data to a csv file:\n```python\ncatalog_assets_df = client.catalog_assets().to_dataframe()\nonly_assets_with_metrics = catalog_assets_df.dropna(subset=[\'metrics\'])\nonly_assets_with_metrics.to_csv("cm_assets_with_metrics.csv")\n```\n\nYou may notice that in that data saved, the "metrics" column for example is a list of json data describing the metrics \noffered and the frequency at which they are available. To help parse this information there is a keyword for all catalog\nendpoint data `secondary_level`:\n```python\ncatalog_assets_df = client.catalog_assets().to_dataframe(secondary_level="metrics")\nonly_assets_with_metrics = catalog_assets_df.dropna(subset=[\'metric\'])\neth_metrics = only_assets_with_metrics[only_assets_with_metrics[\'asset\'] == "eth"]\neth_metrics.to_csv("eth_metrics_granular.csv")\n```\n\nThe above example queries for eth metrics at the level of metrics and frequency, where it will have one row for each \nmetric and frequency related to Ethereum. This allows users to quickly get high level information about exactly what\nis offered from the Coin Metrics API and to make custom queries against the API from there. This example only covers \n`catalog_assets()`, but the pattern can be used across all of our catalog endpoints. \n\n\n## Examples\nThe API Client allows you to chain together workflows for importing, transforming, then exporting Coin Metrics data.\nBelow are examples of common use-cases that can be altered to tailor your specific needs. In addition to the examples \nlisted below, there\'s examples covering all the API methods, found in the [examples directory](https://github.com/coinmetrics/api-client-python/tree/master/examples).\n\n**[Example Notebooks](https://github.com/coinmetrics/api-client-python/tree/master/examples/notebooks)**\n\n* `walkthrough_community.ipynb`: Walks through the basic functionality available using the community client.\n\n**[Asset Metrics](https://github.com/coinmetrics/api-client-python/tree/master/examples/asset_metrics)**\n\n* `bbb_metrics_csv_exporter_using_plain_requests.py`: Queries block-by-block metrics using the `requests` library and exports the output into a CSV file.\n* `bbb_metrics_json_exporter.py`: Queries block-by-block metrics and exports the output into a JSON file.\n* `eod_metrics_csv_exporter.py`: Exports a set of user-defined metrics and assets published at end-of-day and exports the output into a CSV file.\n* `reference_rates_json_exporter.py`: Queries Coin Metrics Reference Rates at a user-defined frequency for a set of assets, then exports the output into a JSON file.\n\n**[Market Data](https://github.com/coinmetrics/api-client-python/tree/master/examples/market_data)** \n\n* `books_json_exporter.py`: Queries market orderbook data then exports the output into a JSON file.\n* `candles_json_exporter.py`: Queries market candles data then exports the output into a JSON file.\n* `funding_rates_json_exporter.py`: Queries market funding rates data then exports the output into a JSON file.\n* `trades_csv_exporter.py`: Queries market trades data then exports the output into a CSV file.\n* `trades_json_exporter.py`: Queries market trades data then exports the output into a JSON file.\n\n## Getting timeseries data\n\nFor getting timeseries data you want to use methods of the client class that start with `get_`. It\'s important to note\nthat the timeseries endpoints return data of a parent class type `DataCollection`. The `DataCollection` class is meant\nto support a variety of different data export and data manipulation use cases, so just calling one of the client\nmethods such as `data = client.get_market_trades(markets="coinbase-btc-usd-spot")` will not actually retrieve the data related\nto this API call. You must then call a function on this `DataCollection` such as `data.export_to_csv("coinbase_btc_usd_spot_trades.csv)`\nor `data.to_dataframe()` in order to access the data. There is more explicit examples below.If you are curious to see\nhow the API calls are being made and with what parameters, instantiating the client with the `verbose` argument like \n`CoinMetricsClient(api_key=<YOUR_API_KEY>, verbose=True)` will print the API calls as well as information on performance to console. \n\nFor example if you want to get a bunch of market data trades for coinbase btc-usd pair you can run something similar to the following:\n\n```\nfor trade in client.get_market_trades(\n    markets=\'coinbase-btc-usd-spot\', \n    start_time=\'2020-01-01\', \n    end_time=\'2020-01-03\',\n    limit_per_market=10\n):\n    print(trade)\n```\nThis example uses the `DataCollection` as a Python iterator, so with each iteration of the Python for loop it will\ncall the Coin Metrics API and return data. The default `page_size` for calls to the API is 100, so each call will return\n100 trades until it reaches the end of the query. To get more trades in each API call, you can add the parameter\n`page_size` to the `.get_market_trades()` method call, up to a maximum of 10000. \n\nOr if you want to see daily btc asset metrics you can use something like this:\n\n```\nfor metric_data in client.get_asset_metrics(assets=\'btc\', \n                                            metrics=[\'ReferenceRateUSD\', \'BlkHgt\', \'AdrActCnt\',  \n                                                     \'AdrActRecCnt\', \'FlowOutBFXUSD\'], \n                                            frequency=\'1d\',\n                                            limit_per_asset=10):\n    print(metric_data)\n```\nThis will print you the requested metrics for all the days where we have any of the metrics present.\n\n\n### DataFrames\n_(New in >=`2021.9.30.14.30`)_\n\nTimeseries data can be transformed into a pandas dataframe by using the `to_dataframe()` method. The code snippet below shows how:\n```\nimport pandas as pd\nfrom coinmetrics.api_client import CoinMetricsClient\nfrom os import environ\n\nclient = CoinMetricsClient()\ntrades = client.get_market_trades(\n    markets=\'coinbase-btc-usd-spot\', \n    start_time=\'2021-09-19T00:00:00Z\', \n    limit_per_market=10\n)\ntrades_df = trades.to_dataframe()\nprint(trades_df.head())\n\n```\nIf you want to use dataframes, then you will need to install pandas\n\n**Notes**\n\n- This only works with requests that return the type `DataCollection`. Thus, `catalog` requests, which return lists cannot be returned as dataframes.\n  Please see the [API Client Spec](https://coinmetrics.github.io/api-client-python/site/api_client.html) for a full list\n  of requests and their return types.\n- API restrictions apply. Some requests may return empty results due to limited access to the API from you API key.\n\n#### Type Conversion \n_(New in >=`2021.12.17.18.00`)_\n\nAs of version `2021.12.17.18.00` or later, outputs from the  `to_dataframe` function automatically convert the dtypes for a dataframe to the optimal pandas types.\n```python\nmetrics_list = [\'volume_trusted_spot_usd_1d\', \'SplyFF\', \'AdrBalUSD1Cnt\']\nasset_list = [\'btc\',\'xmr\']\nstart_time=\'2021-12-01\'\ndf_metrics = client.get_asset_metrics(\n  assets=asset_list, metrics=metrics_list, start_time=start_time, limit_per_asset=3\n).to_dataframe()\nprint(df_metrics.dtypes)\n```\n\n```\nasset                          string\ntime                           datetime64[ns, tzutc()]\nAdrBalUSD1Cnt                   Int64\nSplyFF                        Float64\nvolume_trusted_spot_usd_1d    Float64\ndtype: object\n```\n\nThis can be turned off by setting `optimize_pandas_types=False`\n\nAlternatively, you can manually enter your own type conversion by passing in a dictionary for `dtype_mapper`. This can be done in conjunction with pandas\' built in type optimizations.\n```python\nmapper = {\n  \'SplyFF\': \'Float64\',\n  \'AdrBalUSD1Cnt\': \'Int64\',\n}\ndf_mapped = client.get_asset_metrics(\n  assets=asset_list, metrics=metrics_list, start_time=start_time, limit_per_asset=3\n).to_dataframe(dtype_mapper=mapper, optimize_pandas_types=True)\nprint(df_mapped.dtypes)\n```\n\n```\nasset                                          object\ntime                          datetime64[ns, tzutc()]\nAdrBalUSD1Cnt                                   Int64\nSplyFF                                        Float64\nvolume_trusted_spot_usd_1d                    float64\ndtype: object\n```\n\nOr as strictly the only types in the dataframe\n\n```python\ndtype_mapper = {\n    \'ReferenceRateUSD\': np.float64,\n    \'time\': np.datetime64\n}\ndf = client.get_asset_metrics(\n  assets=\'btc\', metrics=\'ReferenceRateUSD\', start_time=\'2022-06-15\', limit_per_asset=1\n).to_dataframe(dtype_mapper=dtype_mapper, optimize_pandas_types=False)\ndf.info()\n```\n```\nRangeIndex: 1 entries, 0 to 0\nData columns (total 3 columns):\n #   Column            Non-Null Count  Dtype         \n---  ------            --------------  -----         \n 0   asset             1 non-null      object        \n 1   time              1 non-null      datetime64[ns]\n 2   ReferenceRateUSD  1 non-null      float64       \ndtypes: datetime64[ns](1), float64(1), object(1)\nmemory usage: 152.0+ bytes\n```\n\nNote that in order to pass a custom datetime object, setting a dtype_mapper is mandatory.\n\nPandas type conversion tends to be more performant. But if there are custom operations that must be done using numpy datatypes, this option will let you perform them.\n\n### Exporting to csv and json files:\nYou can also easily export timeseries data to csv and json files with builtin functions on the `DataCollection` type. \nFor example this script will export Coinbase btc and eth trades for a date to csv and json files respectively:\n```python\n    start_date = datetime.date(year=2022, month=1, day=1)\n    end_date = datetime.datetime(year=2022, month=1, day=1)\n    market_trades_btc = client.get_market_trades(page_size=1000, markets="coinbase-btc-usd-spot", start_time=start_date, end_time=end_date)\n    market_trades_btc.export_to_csv("jan_1_2022_coinbase_btc_trades.csv")\n    market_trades_eth = client.get_market_trades(page_size=1000, markets="coinbase-eth-usd-spot", start_time=start_date, end_time=end_date)\n    market_trades_eth.export_to_json("jan_1_2022_coinbase_eth.json")\n```\n\n### Paging\nYou can make the datapoints to iterate from start (default) or from end.\n\nfor that you should use a paging_from argument like the following:\n```\nfrom coinmetrics.api_client import CoinMetricsClient\nfrom coinmetrics.constants import PagingFrom\n\nclient = CoinMetricsClient()\n\nfor metric_data in client.get_asset_metrics(assets=\'btc\', metrics=[\'ReferenceRateUSD\'],\n                                            paging_from=PagingFrom.START):\n    print(metric_data)\n```\n\nPagingFrom.END: is available but by default it will page from the start.\n\n\n### Debugging the API Client\nThere are two additional options for the API Client - `debug_mode` and `verbose`. These two options log network calls \nto the console, and in the case of `debug_mode` it will generate a log file of all the network requests and the time\nit takes to call them. These tools can be used to diagnose issues in your code and also to get a better understanding \nof request times so that users can write more performant code. For example, running the below code:\n```python\nimport os\n\nfrom coinmetrics.api_client import CoinMetricsClient\n\napi_key = os.environ[\'CM_API_KEY\']\n\nif __name__ == \'__main__\':\n    client = CoinMetricsClient(api_key=api_key, debug_mode=True)\n    reference_rates_example = client.get_asset_metrics(assets=[\'btc\', \'algo\', \'eth\'], metrics=[\'ReferenceRateUSD\'])\n    for data in reference_rates_example:\n        continue\n```\n\nThe console output will look like:\n```commandline\n[DEBUG] 2023-01-09 11:01:02,044 - Starting API Client debugging session. logging to stdout and cm_api_client_debug_2023_01_09_11_01_02.txt\n[DEBUG] 2023-01-09 11:01:02,044 - Using coinmetrics version 2022.11.14.16\n[DEBUG] 2023-01-09 11:01:02,044 - Current state of API Client, excluding API KEY: {\'_verify_ssl_certs\': True, \'_api_base_url\': \'https://api.coinmetrics.io/v4\', \'_ws_api_base_url\': \'wss://api.coinmetrics.io/v4\', \'_http_header\': {\'Api-Client-Version\': \'2022.11.14.16\'}, \'_proxies\': {\'http\': None, \'https\': None}, \'debug_mode\': True, \'verbose\': False}\n[DEBUG] 2023-01-09 11:01:02,044 - Attempting to call url: timeseries/asset-metrics with params: {\'assets\': [\'btc\', \'algo\', \'eth\'], \'metrics\': [\'ReferenceRateUSD\'], \'frequency\': None, \'page_size\': None, \'paging_from\': \'start\', \'start_time\': None, \'end_time\': None, \'start_height\': None, \'end_height\': None, \'start_inclusive\': None, \'end_inclusive\': None, \'timezone\': None, \'sort\': None, \'limit_per_asset\': None}\n[DEBUG] 2023-01-09 11:01:02,387 - Response status code: 200 for url: https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=[REDACTED]&assets=btc%2Calgo%2Ceth&metrics=ReferenceRateUSD&paging_from=start took: 0:00:00.342874 response body size (bytes): 9832\n[DEBUG] 2023-01-09 11:01:02,388 - Attempting to call url: timeseries/asset-metrics with params: {\'assets\': [\'btc\', \'algo\', \'eth\'], \'metrics\': [\'ReferenceRateUSD\'], \'frequency\': None, \'page_size\': None, \'paging_from\': \'start\', \'start_time\': None, \'end_time\': None, \'start_height\': None, \'end_height\': None, \'start_inclusive\': None, \'end_inclusive\': None, \'timezone\': None, \'sort\': None, \'limit_per_asset\': None, \'next_page_token\': \'0.MjAxOS0wOS0zMFQwMDowMDowMFo\'}\n[DEBUG] 2023-01-09 11:01:02,559 - Response status code: 200 for url: https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=[REDACTED]&assets=btc%2Calgo%2Ceth&metrics=ReferenceRateUSD&paging_from=start&next_page_token=0.MjAxOS0wOS0zMFQwMDowMDowMFo took: 0:00:00.171487 response body size (bytes): 9857\n```\nThen it can be easier to understand what network calls the API Client is making, and where any issues may exist. If you\nwish to dig even deeper, you may consider modifying the `_send_request()` method of the API Client to log additional \ndata about the state of your environment, or anything else that would help diagnose issues. You will notice a log file\ngenerated in the format `cm_api_client_debug_2023_01_09_11_01_02.txt`. This log file might be helpful for your own use\nor to give more context if you are working with Coin Metrics customer success. \n\n### SSL Certs verification\n\nSometimes your organization network have special rules on SSL certs verification and in this case you might face the\nfollowing error when running the script:\n```text\nSSLError: HTTPSConnectionPool(host=\'api.coinmetrics.io\', port=443): Max retries exceeded with url: <some_url_path> (Caused by SSLError(SSLCertVerificationError(1, \'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)\')))\n```\n\nIn this case, you can pass an option during client initialization to disable ssl verification for requests like this:\n\n```python\n\nclient = CoinMetricsClient(verify_ssl_certs=False)\n```\n\nWe don\'t recommend setting it to False by default and you should make sure you understand the security risks of disabling SSL certs verification.\n\nAdditionally, you may choose to specify the path to the SSL certificates on your machine. This may cause errors where \nPython is unable to locate the certificates on your machine, particularly when using Python virtual environments. \n\n```python\nfrom coinmetrics.api_client import CoinMetricsClient\nSSL_CERT_LOCATION = \'/Users/<USER_NAME>/Library/Python/3.8/lib/python/site-packages/certifi/cacert.pem\'\nclient = CoinMetricsClient(verify_ssl_certs=SSL_CERT_LOCATION)\n```\n\nA quick way to find the certs on your machine is:  \n`python3 -c "import requests; print(requests.certs.where())"`  \nAnd note that this will change based on whether or not you are using a [Python virtual environment or not](https://realpython.com/python-virtual-environments-a-primer/)\n\n### Installing and running coinmetrics package and other python packages behind a secure python network\nRelated to SSL Certs verification, you may have trouble installing and updating PyPi packages to your local environment.\nSo you may need to choose the best solution for your company and environment - either using package managers or\ninstalling offline.\n\n#### Installing using package managers\nFull instructions for setting up your environment to use conda, pip, yarn, npm, etc. can be [found here](https://medium.com/@iffi33/dealing-with-ssl-authentication-on-a-secure-corporate-network-pip-conda-git-npm-yarn-bower-73e5b93fd4b2).\nAdditionally, a workaround to disable SSL verification when installing a trusted Python package is this:  \n```commandline\npip install --trusted-host pypi.python.org <packagename>\n```  \nAlthough it is important to make sure you understand the risks associated with disabling SSL verification and ensure \ncompliance with company policies.\n\n\n\n#### Installing Python packages locally/ offline\nIt may be easier to download and install the package locally. Steps:  \n1. Download the files for the [Coin Metrics API Client from PyPi](https://pypi.org/project/coinmetrics-api-client/#files)\n2. [Install it locally](https://packaging.python.org/en/latest/tutorials/installing-packages/#installing-from-local-archives)\n\n### Requests Proxy\nSometimes your organization has special rules on making requests to third parties and you have to use proxies in order to comply with the rules.\n\nFor proxies that don\'t require auth you can specify them similar to this example:\n```python\n\nclient = CoinMetricsClient(proxy_url=f\'http://<hostname>:<port>\')\n```\n\nFor proxies that require auth, you should be able to specify username and password similar to this example:\n```python\n\nclient = CoinMetricsClient(proxy_url=f\'http://<username>:<password>@<hostname>:<port>\')\n```\n\n## Extended documentation\nFor more information about the available methods in the client please reference [API Client Spec](https://coinmetrics.github.io/api-client-python/site/api_client.html)\n\n',
    'author': 'Coin Metrics',
    'author_email': 'info@coinmetrics.io',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://coinmetrics.github.io/api-client-python/site/index.html',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'extras_require': extras_require,
    'entry_points': entry_points,
    'python_requires': '>=3.7.1,<4.0.0',
}


setup(**setup_kwargs)
