### Setup Project Environment (Bash) Source: https://github.com/santiment/sanpy/blob/master/README.md Installs project dependencies using pipenv. This command installs all necessary packages for local development. ```bash pipenv install ``` -------------------------------- ### Install Dev Dependencies (Bash) Source: https://github.com/santiment/sanpy/blob/master/README.md Installs development-specific dependencies, including testing and linting tools, using pipenv. It installs extras for the project. ```bash pipenv run pip install -e '.[dev]' ``` -------------------------------- ### Install sanpy from PyPI Source: https://github.com/santiment/sanpy/blob/master/README.md Installs the latest version of the sanpy library from the Python Package Index. ```bash pip install sanpy==0.12.3 ``` -------------------------------- ### Initialize Sanpy Strategy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Strategy.ipynb Initializes a Sanpy Strategy object with a specified start date and initial asset. This is the starting point for defining and backtesting trading strategies. ```python index = Strategy(start_dt="2021-01-01", init_asset="dai") ``` -------------------------------- ### Install sanpy with extra packages Source: https://github.com/santiment/sanpy/blob/master/README.md Installs sanpy along with additional dependencies required for utilities like backtesting and event studies. ```bash pip install sanpy[extras] ``` -------------------------------- ### Install Main Dependencies (Bash) Source: https://github.com/santiment/sanpy/blob/master/README.md Installs the main project dependencies in editable mode using pipenv. This command is typically used after cloning the repository. ```bash pipenv run pip install -e . ``` -------------------------------- ### Install Extra Dependencies (Bash) Source: https://github.com/santiment/sanpy/blob/master/README.md Installs extra dependencies for the project using pipenv. This command is used when additional functionalities or integrations are needed. ```bash pipenv run pip install -e '.[extras]' ``` -------------------------------- ### Initialize Backtest Object in Python Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Backtest.ipynb Instantiates the Backtest class, a core component for running financial simulations. It requires the starting date as an argument. ```python backtest = Backtest(START_DT) ``` -------------------------------- ### Get Marketcap, Price USD, Price BTC, and Trading Volume Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches market capitalization, price in USD, price in BTC, and trading volume for a given project. ```APIDOC ## GET prices ### Description Retrieves market cap, price in USD, price in BTC, and trading volume for a specified project within a given date range and interval. ### Method GET ### Endpoint /prices ### Parameters #### Query Parameters - **slug** (string) - Required - The unique identifier of the project. - **from_date** (string) - Required - The start date for the data (YYYY-MM-DD). - **to_date** (string) - Required - The end date for the data (YYYY-MM-DD). - **interval** (string) - Required - The time interval for the data (e.g., '1d', '1w', '1m'). ### Request Example ```python san.get( "prices", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (string) - The timestamp of the data point. - **marketcap** (number) - The market capitalization of the project. - **priceUsd** (number) - The price of the project in USD. - **priceBtc** (number) - The price of the project in BTC. - **volume** (number) - The trading volume of the project. #### Response Example ```json { "datetime": "2018-06-01T00:00:00Z", "marketcap": 77362680, "priceUsd": 1.24380, "priceBtc": 0.000123, "volume": 852857 } ``` ``` -------------------------------- ### Define Start Date for Backtesting in Python Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Backtest.ipynb Sets the starting date for backtesting operations. This variable is crucial for initializing the Backtest object. ```python START_DT = "2020-01-01" ``` -------------------------------- ### Fetch Development Activity by Organization Source: https://github.com/santiment/sanpy/blob/master/README.md Example of fetching development activity for a specific organization using the `selector` parameter. ```APIDOC ## GET /api/get (dev_activity example) ### Description Fetches development activity for a specified organization. ### Method GET ### Endpoint /api/get ### Parameters #### Path Parameters - None #### Query Parameters - **metric** (string) - Must be 'dev_activity'. - **selector** (object) - Required - Specifies the organization. Example: `{"organization": "google"}`. - **from_date** (string) - Optional - Start date in ISO8601 format. - **to_date** (string) - Optional - End date in ISO8601 format. - **interval** (string) - Optional - Data point interval. ### Request Example ```python import san san.get( "dev_activity", selector={"organization": "google"}, from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (datetime) - The timestamp of the data point. - **value** (number) - The development activity count. #### Response Example ```json { "datetime": "2022-01-01T00:00:00+00:00", "value": 176.0 } ``` ``` -------------------------------- ### Define Parameters for Triple Barrier Evaluation Source: https://github.com/santiment/sanpy/blob/master/examples/extras/triple_barrier.ipynb Sets the start date, end date, and resolution for the triple barrier analysis. These parameters control the time window and granularity of the data used for evaluation. ```python FROM_TIMESTAMP = "2020-01-01" TO_TIMESTAMP = "2020-03-20" RESOLUTION = "1d" ``` -------------------------------- ### Fetch Metric by Contract Address Source: https://github.com/santiment/sanpy/blob/master/README.md Example of fetching a metric for a contract address using the `selector` parameter. ```APIDOC ## GET /api/get (contract_transactions_count example) ### Description Fetches a metric (e.g., contract transactions count) for a specific contract address. ### Method GET ### Endpoint /api/get ### Parameters #### Path Parameters - None #### Query Parameters - **metric** (string) - The name of the metric (e.g., 'contract_transactions_count'). - **selector** (object) - Required - Specifies the contract address. Example: `{"contractAddress": "0x00000000219ab540356cBB839Cbe05303d7705Fa"}`. - **from_date** (string) - Optional - Start date in ISO8601 format. - **to_date** (string) - Optional - End date in ISO8601 format. - **interval** (string) - Optional - Data point interval. ### Request Example ```python import san san.get( "contract_transactions_count", selector={"contractAddress": "0x00000000219ab540356cBB839Cbe05303d7705Fa"}, from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (datetime) - The timestamp of the data point. - **value** (number) - The metric value. #### Response Example ```json { "datetime": "2022-01-01T00:00:00+00:00", "value": 90.0 } ``` ``` -------------------------------- ### Import Libraries for Event Study in Sanpy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/event_study.ipynb Imports necessary libraries including date, numpy, and specific functions from the sanpy module for data fetching and event study analysis. These are foundational for the subsequent steps. ```python from datetime import date import numpy as np import san from san.extras.event_study import event_study, signals_format, hypothesis_test ``` -------------------------------- ### Format Signals and Execute Event Study Source: https://github.com/santiment/sanpy/blob/master/examples/extras/event_study.ipynb Formats the defined 'sell' signals using the `signals_format` helper function and then executes the event study using the prepared price data and formatted signals. The `event_study` function analyzes the price movements around the defined signals. The `starting_point` parameter defines the window for analysis relative to the signal event. ```python # Helper function to get the signals in the right format: signals = signals_format(data["sell"], "ETH_close") # Calling the event study: event_study(price, signals, starting_point=30) ``` -------------------------------- ### Fetch Top Holders Metric Source: https://github.com/santiment/sanpy/blob/master/README.md Example of fetching the 'amount_in_top_holders' metric and specifying the number of top holders. ```APIDOC ## GET /api/get (amount_in_top_holders example) ### Description Fetches the 'amount_in_top_holders' metric, allowing specification of the number of top holders to consider. ### Method GET ### Endpoint /api/get ### Parameters #### Path Parameters - None #### Query Parameters - **metric** (string) - Must be 'amount_in_top_holders'. - **selector** (object) - Required - Specifies the slug and optionally the number of top holders. Example: `{"slug": "santiment", "holdersCount": 10}`. - **from_date** (string) - Optional - Start date in ISO8601 format. - **to_date** (string) - Optional - End date in ISO8601 format. - **interval** (string) - Optional - Data point interval. ### Request Example ```python import san san.get( "amount_in_top_holders", selector={"slug": "santiment", "holdersCount": 10}, from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (datetime) - The timestamp of the data point. - **value** (number) - The amount in top holders. #### Response Example ```json { "datetime": "2022-01-01T00:00:00+00:00", "value": 7.391186e+07 } ``` ``` -------------------------------- ### Upgrade sanpy to the latest version Source: https://github.com/santiment/sanpy/blob/master/README.md Updates the installed sanpy library to its most recent release. ```bash pip install --upgrade sanpy ``` -------------------------------- ### Fetch and Format Ethereum Price Data Source: https://github.com/santiment/sanpy/blob/master/examples/extras/triple_barrier.ipynb Retrieves historical daily closing prices for Ethereum from the San API and formats it into a pandas DataFrame. The DataFrame is indexed by datetime and the price column is renamed to 'ethereum' for clarity. ```python prices = pd.DataFrame() prices = pd.DataFrame(san.get("ohlcv/ethereum", from_date="2020-02-01", to_date="2020-05-01", interval="1d").closePriceUsd) prices.rename(columns={"closePriceUsd": "ethereum"}, inplace=True) ``` -------------------------------- ### Get OHLCV Data Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches Open, High, Low, Close prices, Volume, and Marketcap for a specified project. This query cannot be batched. ```APIDOC ## GET ohlcv/{slug} ### Description Retrieves Open, High, Low, Close prices, Volume, and Marketcap for a specified project. This endpoint does not support batching and the `slug`/`selector` argument format is not applicable here. ### Method GET ### Endpoint /ohlcv/{slug} ### Parameters #### Path Parameters - **slug** (string) - Required - The unique identifier of the project. #### Query Parameters - **from_date** (string) - Required - The start date for the data (YYYY-MM-DD). - **to_date** (string) - Required - The end date for the data (YYYY-MM-DD). - **interval** (string) - Required - The time interval for the data (e.g., '1d', '1w', '1m'). ### Request Example ```python san.get( "ohlcv/santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (string) - The timestamp of the data point. - **openPriceUsd** (number) - The opening price in USD. - **closePriceUsd** (number) - The closing price in USD. - **highPriceUsd** (number) - The highest price in USD. - **lowPriceUsd** (number) - The lowest price in USD. - **volume** (number) - The trading volume. - **marketcap** (number) - The market capitalization. #### Response Example ``` datetime openPriceUsd closePriceUsd highPriceUsd lowPriceUsd volume marketcap 2018-06-01 00:00:00+00:00 1.24380 1.27668 1.26599 1.19099 852857 7.736268e+07 2018-06-02 00:00:00+00:00 1.26136 1.30779 1.27612 1.20958 1242520 7.864724e+07 ``` ``` -------------------------------- ### Create and Prepare Trades DataFrame in Python Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Backtest.ipynb Creates a Pandas DataFrame to represent trade data, indexed by date. This example shows trades occurring on a specific date, with the index converted to datetime objects. ```python trades_df = pd.DataFrame({"dt": ["2020-01-04"] * 5}).set_index("dt") trades_df.set_index(pd.to_datetime(trades_df.index), inplace=True) ``` -------------------------------- ### Fetch and Prepare Cryptocurrency Data for Event Study Source: https://github.com/santiment/sanpy/blob/master/examples/extras/event_study.ipynb Fetches historical Open, High, Low, Close, and Volume (OHLCV) data for Bitcoin and Ethereum using the sanpy library. It also retrieves daily active addresses for Ethereum. The data is then processed to calculate log returns and rolling standard deviation for signal generation. Finally, it converts the data to a timezone-naive format suitable for event study analysis. ```python data = san.get("ohlcv/bitcoin") data["bitcoin"] = data.closePriceUsd data["ETH_close"] = san.get("ohlcv/ethereum").closePriceUsd data["daily_active_addresses_ETH"] = san.get("daily_active_addresses/ethereum") data["daa_performance"] = np.log(data["daily_active_addresses_ETH"].pct_change() + 1) data["sd_rolling"] = data["daa_performance"].rolling(100).std() price = data[["ETH_close", "bitcoin"]] price = price.tz_convert(None) # Event Study needs date instead of datetime ``` -------------------------------- ### Get All Available Metrics Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves a list of all available metrics from the Santiment API. This function is useful for exploring the dataset and understanding what data points can be queried. ```python san.available_metrics() ``` -------------------------------- ### Import Libraries for SanPy Triple Barrier Analysis Source: https://github.com/santiment/sanpy/blob/master/examples/extras/triple_barrier.ipynb Imports necessary libraries including san for data fetching, pandas for data manipulation, and seaborn/matplotlib for plotting. These are essential for preparing data and visualizing results. ```python import san import pandas as pd import seaborn as sns from san.extras.triple_barrier import evaluate, plot sns.set() ``` -------------------------------- ### Fetch development activity using selector with organization Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches development activity data for a specific organization using the `get` function with a `selector` parameter. Requires the metric name and a selector dictionary specifying the organization. Includes date range and interval. ```python import san san.get( "dev_activity", selector={"organization": "google"}, from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` -------------------------------- ### Evaluate Signals using Triple Barrier Method Source: https://github.com/santiment/sanpy/blob/master/examples/extras/triple_barrier.ipynb Applies the triple barrier method to the prepared price and signal data to generate trading labels. The 'evaluate' function from san.extras.triple_barrier performs the core logic. ```python labels = evaluate(prices, signals) labels ``` -------------------------------- ### Plot Results of Triple Barrier Evaluation Source: https://github.com/santiment/sanpy/blob/master/examples/extras/triple_barrier.ipynb Visualizes the results of the triple barrier evaluation using the 'plot' function from san.extras.triple_barrier. This helps in understanding the performance of the signals against the price data. ```python plot(prices, labels) ``` -------------------------------- ### Get Price Data with Transformations Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches price data for a given slug and applies transformations like moving average. Supports date range and interval selection. ```APIDOC ## GET price_usd ### Description Fetches the price in USD for a given project slug. Allows for data transformation (e.g., moving average) and aggregation. ### Method GET ### Endpoint /price_usd ### Parameters #### Query Parameters - **slug** (string) - Required - The unique identifier of the project. - **from_date** (string) - Required - The start date for the data (YYYY-MM-DD). - **to_date** (string) - Required - The end date for the data (YYYY-MM-DD). - **interval** (string) - Required - The time interval for the data (e.g., '1d', '1w', '1m'). - **transform** (object) - Optional - A transformation to apply to the data. Supported types: 'moving_average', 'consecutive_differences', 'percent_change'. - **type** (string) - Required if transform is used - The type of transformation. - **moving_average_base** (integer) - Required if type is 'moving_average' - The base period for the moving average. - **aggregation** (string) - Optional - The aggregation method for the results (e.g., 'LAST'). ### Request Example ```python san.get( "price_usd", slug="santiment", from_date="2020-06-01", to_date="2021-06-05", interval="1d", transform={"type": "moving_average", "moving_average_base": 100}, aggregation="LAST" ) ``` ### Response #### Success Response (200) - **datetime** (string) - The timestamp of the data point. - **value** (number) - The transformed price value. #### Response Example ```json { "datetime": "2020-06-01T00:00:00Z", "value": 0.12345 } ``` ``` -------------------------------- ### Get Top Transfers (Python) Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves a list of top token transfers for a project. Supports filtering by 'address' and 'transaction_type' (ALL, OUT, IN). Requires 'slug', 'from_date', and 'to_date'. ```python san.get( "top_transfers", slug="santiment", from_date="utc_now-30d", to_date="utc_now", ) ``` ```python san.get( "top_transfers", slug="santiment", address="0x26e068650ae54b6c1b149e1b926634b07e137b9f", transaction_type="ALL", from_date="utc_now-30d", to_date="utc_now", ) ``` -------------------------------- ### Get Metrics for a Specific Slug Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches a list of all metrics associated with a given slug (cryptocurrency identifier). This helps in discovering metrics relevant to a particular asset. ```python san.available_metrics_for_slug("santiment") ``` -------------------------------- ### Fetch single metric by slug using san.get Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches time-series data for a single metric and asset using the `get` function. Requires the metric name and asset slug, with optional date range and interval. Returns a pandas DataFrame. ```python import san san.get( "price_usd", slug="bitcoin", from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` -------------------------------- ### Fetch metric by contract address using selector Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches time-series data for a metric associated with a contract address using the `get` function with a `selector`. Requires the metric name and a selector dictionary containing the `contractAddress`. Includes date range and interval. ```python import san san.get( "contract_transactions_count", selector={"contractAddress": "0x00000000219ab540356cBB839Cbe05303d7705Fa"}, from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` -------------------------------- ### Prepare Signal Data for Triple Barrier Evaluation Source: https://github.com/santiment/sanpy/blob/master/examples/extras/triple_barrier.ipynb Creates a pandas DataFrame to hold trading signals. It includes columns for 'slug', 'side', and 'datetime', and is indexed by datetime. This structure is required for the triple barrier evaluation function. ```python signals = pd.DataFrame(pd.DataFrame(columns=["slug", "side", "datetime"])) signals["datetime"] = pd.DatetimeIndex( [ "2020-02-06", "2020-02-08", "2020-02-13", "2020-02-15", "2020-04-07", "2020-04-08", "2020-04-19", "2020-04-26", "2020-05-19", ], dtype="datetime64[ns]", name="datetime", freq=None, ) signals["slug"] = "ethereum" signals.set_index("datetime", inplace=True) ``` -------------------------------- ### Fetch Timeseries Data for a Single Metric/Asset Source: https://github.com/santiment/sanpy/blob/master/README.md The `get` function fetches timeseries data for a single metric and asset pair. It supports various parameters to filter and specify the data range and interval. ```APIDOC ## GET /api/get ### Description Fetches timeseries data for a single metric and asset pair. ### Method GET ### Endpoint /api/get ### Parameters #### Path Parameters - None #### Query Parameters - **metric** (string) - Required - The name of the metric to fetch. - **slug** (string) - Required (if not using selector) - The project identifier. - **selector** (object) - Optional - Allows for more flexible selection of the target (e.g., organization, contract address, holdersCount). - **from_date** (string) - Optional - Start date in ISO8601 format. Defaults to 1 year ago. - **to_date** (string) - Optional - End date in ISO8601 format. Defaults to now. - **interval** (string) - Optional - Data point interval (e.g., '1d', '1h'). Defaults to '1d'. ### Request Example ```python import san san.get( "price_usd", slug="bitcoin", from_date="2022-01-01", to_date="2022-01-05", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (datetime) - The timestamp of the data point. - **value** (number) - The metric value for the given timestamp. #### Response Example ```json { "datetime": "2022-01-01T00:00:00+00:00", "value": 47686.811509 } ``` ``` -------------------------------- ### Get Token Top Transactions (Python) Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches the top transactions for a given token of a project. Accepts 'slug', 'from_date', 'to_date', and 'limit' as parameters. The output includes transaction details like addresses, hash, and value. ```python san.get( "token_top_transactions", slug="santiment", from_date="2019-04-18", to_date="2019-04-30", limit=5 ) ``` -------------------------------- ### Execute SQL Query and Get DataFrame Source: https://github.com/santiment/sanpy/blob/master/README.md Executes a given SQL query against the Santiment database and returns the result as a pandas DataFrame. It requires a valid API key for execution. The `set_index` parameter can be used to set a specific column as the DataFrame index. ```python import san san.execute_sql(query="SELECT * FROM daily_metrics_v2 LIMIT 5") ``` ```python import san san.execute_sql(query="SELECT * FROM daily_metrics_v2 LIMIT 5", set_index="dt") ``` -------------------------------- ### Perform Hypothesis Test on Event Study Signals Source: https://github.com/santiment/sanpy/blob/master/examples/extras/event_study.ipynb Conducts a hypothesis test on the event study results to determine the statistical significance of the generated signals. It uses the `hypothesis_test` function with the price data, signals, and specifies Bitcoin as the benchmark for comparison. The `intercept` and `CI` parameters control the statistical model and confidence interval for the test. ```python # Calling the hypothesis test: hypothesis_test(price, signals, starting_point=30, benchmark="bitcoin", intercept=True, CI=0.95) ``` -------------------------------- ### Define Buy and Sell Signals based on Volatility Source: https://github.com/santiment/sanpy/blob/master/examples/extras/event_study.ipynb Defines buy and sell signals based on the deviation of 'daily active addresses' performance from its rolling standard deviation. A buy signal is triggered when the performance is more than two standard deviations below the mean, and a sell signal is triggered when it's more than two standard deviations above the mean. This logic helps identify potential trading opportunities based on unusual volatility. ```python # Defining signals: # Buy Signal: Is the current trend lower than two standard deviations? data["buy"] = data["daa_performance"] < (data["sd_rolling"] * (-1) * 2) # Sell Signal: Is the current trend higher than two standard deviations? data["sell"] = data["daa_performance"] > (data["sd_rolling"] * 2) ``` -------------------------------- ### Batching Multiple Queries with AsyncBatch Source: https://github.com/santiment/sanpy/blob/master/README.md Illustrates using the `AsyncBatch` class for concurrent execution of queries across separate HTTP requests, which is the recommended approach. It also shows fetching data for multiple assets using `get_many`. Dependencies: `san` library. ```python from san import AsyncBatch batch = AsyncBatch() batch.get( "daily_active_addresses", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) batch.get_many( "daily_active_addresses", slugs=["bitcoin", "ethereum"], from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) [daa, daa_many] = batch.execute(max_workers=10) ``` -------------------------------- ### Batching Queries with Batch and AsyncBatch Source: https://github.com/santiment/sanpy/blob/master/README.md Demonstrates how to use the Batch and AsyncBatch classes to execute multiple queries efficiently. AsyncBatch is recommended for concurrent execution. ```APIDOC ## Batching Queries SanPy provides `Batch` and `AsyncBatch` classes for executing multiple queries in batches. `AsyncBatch` is recommended for concurrent execution. ### Batch Class The `Batch` class combines queries into a single GraphQL document, suitable for lightweight queries to avoid complexity issues. ```python from san import Batch batch = Batch() batch.get( "daily_active_addresses", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) batch.get( "transaction_volume", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) [daa, trx_volume] = batch.execute() ``` ### AsyncBatch Class The `AsyncBatch` class executes queries in separate HTTP requests concurrently, controlled by `max_workers`. ```python from san import AsyncBatch batch = AsyncBatch() batch.get( "daily_active_addresses", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) batch.get_many( "daily_active_addresses", slugs=["bitcoin", "ethereum"], from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) [daa, daa_many] = batch.execute(max_workers=10) ``` ``` -------------------------------- ### Build Portfolio with Sanpy Strategy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Strategy.ipynb Builds the investment portfolio for a specified date range using the defined strategy, signals, and price data. This simulates the strategy's performance over time. ```python index.build_portfolio("2021-01-01", "2021-01-03") ``` -------------------------------- ### Batching Multiple Queries with Batch Source: https://github.com/santiment/sanpy/blob/master/README.md Demonstrates how to use the `Batch` class to combine multiple queries into a single HTTP request. This is suitable for lightweight queries as complexity accumulates. Dependencies: `san` library. ```python from san import Batch batch = Batch() batch.get( "daily_active_addresses", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) batch.get( "transaction_volume", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) [daa, trx_volume] = batch.execute() ``` -------------------------------- ### Get Historical Balance Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches the historical balance for an ERC20 token or an Ethereum address within a specified interval. ```APIDOC ## GET historical_balance ### Description Retrieves the historical balance for a given ERC20 token or Ethereum address within a specified date range and interval. ### Method GET ### Endpoint /historical_balance ### Parameters #### Query Parameters - **slug** (string) - Required - The unique identifier of the project or token. - **address** (string) - Required - The Ethereum address for which to fetch the balance. - **from_date** (string) - Required - The start date for the data (YYYY-MM-DD). - **to_date** (string) - Required - The end date for the data (YYYY-MM-DD). - **interval** (string) - Required - The time interval for the data (e.g., '1d', '1w', '1m'). ### Request Example ```python san.get( "historical_balance", slug="santiment", address="0x1f3df0b8390bb8e9e322972c5e75583e87608ec2", from_date="2019-04-18", to_date="2019-04-23", interval="1d" ) ``` ### Response #### Success Response (200) - **datetime** (string) - The timestamp of the data point. - **balance** (number) - The balance at the given timestamp. #### Response Example ``` datetime balance 2019-04-18 00:00:00+00:00 382338.33 2019-04-19 00:00:00+00:00 382338.33 2019-04-20 00:00:00+00:00 382338.33 ``` ``` -------------------------------- ### Fetch All Projects (Python) Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches a list of all projects, including their name, slug, ticker, and total supply. This is useful for retrieving a general overview of available projects. ```python import san san.get("projects/all") ``` -------------------------------- ### Add and View Reserve Assets in Sanpy Strategy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Strategy.ipynb Demonstrates how to add reserve assets to the strategy, specifying a date range for each asset. It also shows how to access the current list of reserve assets. ```python # add reserve asset index.assets.add(assets={"dai": ["2021-01-01", "2021-01-04"]}, assets_type="r") index.assets.reserve_assets ``` -------------------------------- ### Get Ethereum Top Transactions Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches the top ETH transactions for a project's team wallets, categorized by transaction type. ```APIDOC ## GET eth_top_transactions ### Description Retrieves the top Ethereum transactions associated with a project's team wallets. Transactions can be filtered by type (ALL, IN, OUT). ### Method GET ### Endpoint /eth_top_transactions ### Parameters #### Query Parameters - **slug** (string) - Required - The unique identifier of the project. - **from_date** (string) - Required - The start date for the data (YYYY-MM-DD). - **to_date** (string) - Required - The end date for the data (YYYY-MM-DD). - **limit** (integer) - Optional - The maximum number of transactions to return. - **transaction_type** (string) - Optional - The type of transactions to fetch ('ALL', 'IN', 'OUT'). Defaults to 'ALL'. ### Request Example ```python san.get( "eth_top_transactions", slug="santiment", from_date="2019-04-18", to_date="2019-04-30", limit=5, transaction_type="ALL" ) ``` ### Response #### Success Response (200) - **datetime** (string) - The timestamp of the transaction. - **fromAddress** (string) - The sender's address. - **fromAddressInExchange** (boolean) - Indicates if the sender address is on an exchange. - **toAddress** (string) - The recipient's address. - **toAddressInExchange** (boolean) - Indicates if the recipient address is on an exchange. - **trxHash** (string) - The transaction hash. - **trxValue** (number) - The value of the transaction in ETH. #### Response Example ``` datetime fromAddress fromAddressInExchange toAddress toAddressInExchange trxHash trxValue 2019-04-29 21:33:31+00:00 0xe76fe52a251c8f... False 0x45d6275d9496b... False 0x776cd57382456a... 100.00 2019-04-29 21:21:18+00:00 0xe76fe52a251c8f... False 0x468bdccdc334f... False 0x848414fb5c382f... 40.95 ``` ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/santiment/sanpy/blob/master/README.md Executes unit tests for the project using pytest. This command helps verify the correctness of individual code components. ```bash pipenv run pytest ``` -------------------------------- ### Format Code with Ruff (Bash) Source: https://github.com/santiment/sanpy/blob/master/README.md Formats the project's code using Ruff, a fast Python linter and formatter. This command ensures consistent code style across the project. ```bash ruff format ``` -------------------------------- ### Fetch Marketcap, Price USD, and Trading Volume Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves market capitalization, price in USD, and trading volume data for a specified project. Requires the project slug, date range, and data interval. This endpoint provides a summary of market performance. ```python san.get( "prices", slug="santiment", from_date="2018-06-01", to_date="2018-06-05", interval="1d" ) ``` -------------------------------- ### Finding Metric Availability Since Source: https://github.com/santiment/sanpy/blob/master/README.md Demonstrates how to find the earliest available date for a specific metric and asset pair using `available_metric_for_slug_since`. Dependencies: `san` library. ```python san.available_metric_for_slug_since(metric="daily_active_addresses", slug="santiment") ``` -------------------------------- ### Create and Prepare Prices DataFrame in Python Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Backtest.ipynb Constructs a Pandas DataFrame containing asset price data over specified dates. It includes 'dt', 'asset', and 'price' columns, with the 'dt' column converted to a datetime index. ```python prices_df = pd.DataFrame( { "dt": [ "2020-01-01", "2020-01-01", "2020-01-01", "2020-01-02", "2020-01-02", "2020-01-02", "2020-01-03", "2020-01-03", "2020-01-03", "2020-01-04", "2020-01-04", "2020-01-04", "2020-01-05", "2020-01-05", "2020-01-05", ], "asset": [ "eth", "uni", "maker", ] * 5, "price": [ 1000, 100, 500, 1500, 100, 500, 1800, 80, 500, 2250, 100, 500, 2250, 100, 500, ], } ).set_index("dt") prices_df.set_index(pd.to_datetime(prices_df.index), inplace=True) ``` -------------------------------- ### Fetch All Projects Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves a list of all projects tracked by Santiment, including their name, slug, ticker, and total supply. ```APIDOC ## GET /projects/all ### Description Fetches a list of all projects available in the Santiment API. ### Method GET ### Endpoint /projects/all ### Parameters None ### Request Example ```python import san san.get("projects/all") ``` ### Response #### Success Response (200) - **name** (str) - The name of the project. - **slug** (str) - The unique slug identifier for the project. - **ticker** (str) - The ticker symbol for the project's cryptocurrency. - **totalSupply** (str) - The total supply of the cryptocurrency. #### Response Example ``` name slug ticker totalSupply 0 0chain 0chain ZCN 400000000 1 0x 0x ZRX 1000000000 2 0xBitcoin 0xbtc 0xBTC 20999984 ... ``` ``` -------------------------------- ### Get Emerging Trends (Python) Source: https://github.com/santiment/sanpy/blob/master/README.md Fetches emerging trends based on textual data over a specified period. Requires 'from_date', 'to_date', 'interval', and 'size'. Returns data with a score and associated word. ```python san.get( "emerging_trends", from_date="2019-07-01", to_date="2019-07-02", interval="1d", size=5 ) ``` -------------------------------- ### Import Backtest and Pandas in Python Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Backtest.ipynb Imports the necessary libraries, pandas for data manipulation and Backtest from san.extras for backtesting functionalities. ```python import pandas as pd from san.extras.backtest import Backtest ``` -------------------------------- ### Create and Prepare Portfolio DataFrame in Python Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Backtest.ipynb Generates a Pandas DataFrame representing portfolio holdings over time, including asset and share information. The DataFrame is indexed by date and ensures the date index is converted to datetime objects. ```python portfolio_df = pd.DataFrame( { "dt": [ "2020-01-01", "2020-01-01", "2020-01-02", "2020-01-02", "2020-01-03", "2020-01-03", "2020-01-04", "2020-01-04", "2020-01-04", "2020-01-05", "2020-01-05", "2020-01-05", ], "asset": ["eth", "uni", "eth", "uni", "eth", "uni", "eth", "uni", "maker", "eth", "uni", "maker"], "share": [0.5, 0.5, 0.6, 0.4, 0.7, 0.3, 0.5, 0.25, 0.25, 0.5, 0.25, 0.25], } ).set_index("dt") portfolio_df.set_index(pd.to_datetime(portfolio_df.index), inplace=True) ``` -------------------------------- ### Fetching Metric Complexity Source: https://github.com/santiment/sanpy/blob/master/README.md Demonstrates how to check the complexity of a specific metric request using `metric_complexity`. This helps in understanding potential rate limit issues or planning query breakdowns. Dependencies: `san` library. ```python san.metric_complexity( metric="price_usd", from_date="2020-01-01", to_date="2020-02-20", interval="1d" ) ``` -------------------------------- ### List Available Projects Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves a list of all projects available in the Santiment API, including their name, slug, ticker, and total supply. ```APIDOC ## GET projects/all ### Description Returns a DataFrame containing all projects available in the Santiment API. Note that not all metrics are available for every project. ### Method GET ### Endpoint /projects/all ### Parameters No parameters required. ### Request Example ```python san.get("projects/all") ``` ### Response #### Success Response (200) A DataFrame with the following columns: - **name** (string) - The name of the project. - **slug** (string) - The unique identifier of the project. - **ticker** (string) - The ticker symbol of the project. - **totalSupply** (string) - The total supply of the project's token. #### Response Example ``` name slug ticker totalSupply 0 0chain 0chain ZCN 400000000 1 0x 0x ZRX 1000000000 2 0xBitcoin 0xbtc 0xBTC 20999984 3 0xcert Protocol 0xcert ZXC 500000000 4 1World 1world 1WO 37219453 ``` ``` -------------------------------- ### View Built Portfolio in Sanpy Strategy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Strategy.ipynb Displays the resulting portfolio composition after the build_portfolio operation. It shows the assets held and their respective shares on a given date. ```python index.portfolio ``` -------------------------------- ### Prepare Buy Signals for Sanpy Strategy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Strategy.ipynb Prepares a Pandas DataFrame for buy signals, including the date, asset, trade percentage, and decision delay. This data will be used to inform buying decisions within the strategy. ```python buy_signals = pd.DataFrame( {"dt": ["2021-01-05", "2021-01-05", "2021-02-10", "2021-03-10"], "asset": ["ethereum", "uniswap", "ethereum", "uniswap"]} ) buy_signals["trade_percantage"] = buy_signals.apply(lambda x: 0.5 if x["asset"] == "ethereum" else 0.8, axis=1) buy_signals["decision_delay"] = datetime.timedelta(days=2) sell_signals_1 = pd.DataFrame({"dt": ["2021-02-05", "2021-03-15"], "asset": ["ethereum", "uniswap"]}) sell_signals_2 = pd.DataFrame({"dt": ["2021-03-01"], "asset": ["uniswap"]}) ``` -------------------------------- ### Get ETH Spent Over Time (Python) Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves the amount of ETH spent over a specified time period from the project's team wallet. Requires 'slug', 'from_date', 'to_date', and 'interval' parameters. Returns a time-series dataset of ETH spent. ```python san.get( "eth_spent_over_time", slug="santiment", from_date="2019-04-18", to_date="2019-04-23", interval="1d" ) ``` -------------------------------- ### Prepare Price Data for Sanpy Strategy Source: https://github.com/santiment/sanpy/blob/master/examples/extras/Strategy.ipynb Constructs a Pandas DataFrame containing historical price data for multiple assets. This data is crucial for backtesting and portfolio simulation. ```python prices = pd.DataFrame( list(itertools.product(["2021-01-01", "2021-01-02", "2021-01-03"], ["ethereum", "dai", "uniswap"])), columns=["dt", "asset"] ).set_index("dt") prices["price"] = [4000, 1, 100, 4100, 1, 90, 4200, 1, 110] ``` -------------------------------- ### Fetch All Available Projects Source: https://github.com/santiment/sanpy/blob/master/README.md Retrieves a list of all projects available in the Santiment API. The result is a DataFrame containing project details like name, slug, ticker, and total supply. The slug is essential for fetching metrics for specific projects. ```python san.get("projects/all") ```