LogoLogo
  • Kaiko Knowledge Hub
  • General
    • 👋Introduction
    • 🏎️Getting Started
      • API input
      • API output
        • "taker_side_sell" Explained
        • Market open and close
        • Timestamp
      • Authentication
      • Data versioning
      • Envelope
      • Error codes
      • Pagination
      • Rate limiting
  • Data Feeds
    • Introduction
    • Level 1 & Level 2 Data
      • Level 1 Aggregations
        • Trade Count, OHLCV, & VWAP
          • OHLCV only
          • VWAP only
      • Level 1 Tick-Level
        • All trades
        • Derivative liquidation events
        • Borrows, repayments, liquidations, and withdrawals
      • Level 2 Aggregations
        • Market depth (snapshot)
        • Market depth (aggregation)
        • Price slippage (snapshot)
        • Price slippage (aggregation)
        • Bid-ask spread (aggregation)
        • Tokens in a liquidity pool
          • Tokens in a liquidity pool (Uniswap v3)
        • Interest rates, borrowed and deposited amounts
        • Raw order book snapshot
          • Raw order book snapshot + market depth, bid/ask spread & price slippage
      • Level 2 Tick-Level
        • Mints and burns
    • Reference Data
      • Free tier
        • Asset codes
        • Exchange codes
        • Exchange trading pair codes (instruments)
        • Lending protocol codes
        • Blockchain codes
      • Advanced tier
        • Derivatives contract details
        • Derivatives price details
      • Premium tier
        • Market capitalization and circulating supply (BETA)
  • ANALYTICS Solutions
    • Introduction
    • Kaiko Fair Market Value
      • Kaiko Fair Market Value (Direct prices for high liquidity pairs)
      • Kaiko Fair Market Value (Synthetic prices for low liquidity pairs)
        • Convert with Oanda FX Rates
    • Kaiko Derivatives Risk Indicators
      • Exchange-provided metrics
      • Token-level liquidation volumes
      • Implied volatility calculation - smile
      • Implied volatility calculation - surface
    • Kaiko Portfolio Risk & Performance
      • Value at risk calculation
      • Custom valuation
  • Monitoring Solutions
    • Kaiko Market Explorer
      • Assets
      • Exchanges
    • Kaiko Blockchain Monitoring
      • Ethereum Wallets
        • Balances and transactions
      • Bitcoin Wallets
        • Balances
        • Transaction
      • Solana Wallets
        • Balances and transactions
      • Provenance Wallets
        • Balances and transactions
  • Misc & Legacy endpoints
    • CME
Powered by GitBook
On this page
  • What is this endpoint for?
  • Endpoint
  • Parameters
  • Fields
  • Request examples
  • Response example

Was this helpful?

Export as PDF
  1. ANALYTICS Solutions
  2. Kaiko Portfolio Risk & Performance

Value at risk calculation

What is this endpoint for?

Thuis endpoints helps you calculate value at risk. Computed by a proprietary and thoroughly backtested methodology that accounts for the idiosyncrasies of crypto market structure. By convention it's a forecasting VaR, i.e. the prediction of the potential loss for the next day.

Endpoint

https://us.market-api.kaiko.io/v2/data/analytics.v2/value_at_risk

Parameters

Parameter
Required
Description

bases

Yes

Total must match quantities below. The order of bases and their respective quantities must match in the request.

quote

Yes

quantities

Yes

Quantities list of base asset in the portfolio. Must match the number of bases. The order of quantities and their respective bases must match in the request.

risk_level

Yes

The Value at Risk confidence level. Min: 0.90 (included) Max: 1 (excluded)

start_time

Yes

First fixing of the calculation in ISO 8601 (inclusive).

end_time

Yes

Last fixing of the calculation in ISO 8601 (inclusive).

sources

No

boolean. If true, returns all pair prices which were used to compute the Value at Risk. Default: false

Fields

Parameter
Description

var_time

The time at which the VaR is computed.

value_at_risk

Composed of two fields: value and risk_level (the Value at Risk estimator at the specified risk_level.)

additional_vars

List of additional VaRs for standard risk levels.

pair

The constituent pair. (showing only when sources is set to be true)

ref_price

The reference price per asset. (showing only when sources is set to be true)

date

The date of the reference price. (showing only when sources is set to be true)

Request examples

curl --compressed -H 'Accept: application/json' -H 'X-Api-Key: <client-api-key>' \
'https://us.market-api.kaiko.io/v2/data/analytics.v2/value_at_risk?bases=eth,btc,ltc&quantities=3,2,5&quote=usd&risk_level=0.95&start_time=2021-12-01T00:00:00.000Z&end_time=2022-01-31T00:00:00.000Z&sources=true'
##### 1. Import dependencies #####
import requests
import pandas as pd

##### 2. Choose the value of the query's parameters #####
# ---- Required parameters ---- #
bases = "btc,eth"
quote = "usd"
quantities = "1,10"
risk_level = "0.95"
start_time = "2021-12-01T00:00:00.000Z"
end_time = "2022-01-31T00:00:00.000Z"

# ---- Optional parameters ---- #
sources = None

# ---- API key configuration ---- #
api_key = "YOUR_API_KEY"

##### 3. Get the data #####
# ---- Function to run an API call ---- # 
# Get the data in a dataframe --------- # 

def get_kaiko_data(api_key: str, bases: str, quote: str, quantities: str, risk_level: str, start_time: str, end_time: str, sources: bool = None):
    headers = {'Accept': 'application/json', 'X-Api-Key': api_key}
    
    url = f'https://us.market-api.kaiko.io/v2/data/analytics.v2/value_at_risk'
    params = {
        "bases": bases,
        "quote": quote,
        "quantities": quantities,
        "risk_level": risk_level,
        "start_time": start_time,
        "end_time": end_time,
        "sources": sources
    }

    try:
        res = requests.get(url, headers=headers, params=params)
        res.raise_for_status() 
        data = res.json()
        if 'data' not in data:
            print("No data returned.")
            return pd.DataFrame() 
        df = pd.DataFrame(data['data'])

        # Handle pagination with continuation token
        while 'next_url' in data:
            next_url = data['next_url']
            if next_url is None:
                break
            res = requests.get(next_url, headers=headers)
            res.raise_for_status()
            data = res.json()
            if 'data' in data:
                df = pd.concat([df, pd.DataFrame(data['data'])], ignore_index=True)
        return df

    except requests.exceptions.RequestException as e:
        print(f"API request error: {e}")
        return pd.DataFrame() 

# ---- Get the data ---- #
df = get_kaiko_data(api_key=api_key, bases=bases, quote=quote, quantities=quantities, risk_level=risk_level, start_time=start_time, end_time=end_time, sources=sources)
print (df)

Response example

{"query": {
        "bases": "eth,btc,ltc",
        "quote": "usd",
        "quantities": "3,2,5",
        "risk_level": "0.95",
        "sources": true,
        "data_version": "v2",
        "commodity": "analytics",
        "request_time": "2024-12-02T14:57:10.523Z"
    },
    "time": "2024-12-02T14:57:11.037Z",
    "timestamp": 1733151431037,
    "data": [
        {
            "var_time": 1638316800000,
            "value_at_risk": {
                "value": 7348.431318368653,
                "risk_level": 0.95
            },
            "additional_vars": [
                {
                    "value": 6283.239075888689,
                    "risk_level": 0.9
                },
                {
                    "value": 7348.431318368653,
                    "risk_level": 0.95
                },
                {
                    "value": 10285.468412415725,
                    "risk_level": 0.975
                },
                {
                    "value": 10711.839781569755,
                    "risk_level": 0.99
                }
            ]
        },
        {
            "var_time": 1638403200000,
            "value_at_risk": {
                "value": 7300.740323399054,
                "risk_level": 0.95
            },
            "additional_vars": [
                {
                    "value": 6243.422441930624,
                    "risk_level": 0.9
                },
                /*...*/ 
            ]
        },,
    /*...*/ 
    ]
 "sources": {
        "prices": [
            {
                "pair": "eth-usd",
                "prices": [
                    {
                        "ref_price": 611.8140773650796,
                        "date": {
                            "seconds": 1606780800
                        }
                    },
                    /*...*/ 
                ]
            },
            {
                "pair": "btc-usd",
                "prices": [
                    {
                        "ref_price": 19588.910928118505,
                        "date": {
                            "seconds": 1606780800
                        }
                    },
                    /*...*/ 
                ]
            },
            /*...*/ 
        ]
    }
  "quantities": [3, 2, 5],
  "start_date": {"seconds": 1638403200},
  "end_date": {"seconds": 1643673600},
  "risk_level": 0.95,
  "additional_risk_levels": [0.9, 0.95, 0.975, 0.99],
  "decay": 30,
  "bases": ["eth", "btc", "ltc"]}   
PreviousKaiko Portfolio Risk & PerformanceNextCustom valuation

Last updated 2 months ago

Was this helpful?

List of portfolio base components. See

The fiat currency.

Asset codes
Asset codes