Metadata-Version: 2.4
Name: kalshi-python-sdk
Version: 1.0.0
Summary: Institutional Python SDK and Quantitative Analytics Engine for Kalshi Prediction Markets
Author: NaxosData Quant Engineering & William Gonda
Author-email: NaxosData Quant Engineering <research@naxosdata.com>, William Gonda <william@naxosdata.com>
License: MIT
Project-URL: Homepage, https://naxosdata.com
Project-URL: Documentation, https://github.com/nexosdata/kalshi-python-sdk
Project-URL: Repository, https://github.com/nexosdata/kalshi-python-sdk
Project-URL: Tracker, https://github.com/nexosdata/kalshi-python-sdk/issues
Keywords: kalshi python sdk,kalshi api python,kalshi trading library,kalshi client asyncio,cftc prediction market python,prediction markets,binary options,event contracts,quantitative finance,orderbook analytics
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Dynamic: author
Dynamic: license-file
Dynamic: requires-python

# Kalshi Python SDK

[![Python Version](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![CFTC Rule 40.2](https://img.shields.io/badge/CFTC-Rule_40.2_Compliant-emerald.svg)](https://www.cftc.gov/)
[![AsyncIO](https://img.shields.io/badge/AsyncIO-Native-purple.svg)](https://docs.python.org/3/library/asyncio.html)
[![Gateway](https://img.shields.io/badge/NaxosData-API_Gateway-orange.svg)](https://naxosdata.com)
[![Tests](https://img.shields.io/badge/tests-59%20passed%20(100%25)-brightgreen.svg)]()

**kalshi-python-sdk** is the premier **kalshi python sdk** and institutional quantitative library for algorithmic trading on Kalshi, the premier CFTC-regulated designated contract market (DCM). Engineered for quantitative hedge funds, prop desks, and systematic prediction market traders, this **kalshi trading library** delivers high-throughput **kalshi client asyncio** execution, exact **cftc prediction market python** fee schedule compliance, and advanced derivatives analytics including Black-Scholes digital option implied volatility inversion, hazard rate term structure modeling, and Kyle's lambda microstructure spread compression.

Whether interfacing with real-time markets through the **kalshi api python** or routing orders via the institutional [NaxosData](https://naxosdata.com) Gateway (`/api/v1/orderbooks/KALSHI/...`, `/api/v1/markets?venue=KALSHI`), this repository provides strong typing (Pydantic v2), sub-millisecond execution modeling, zero-dependency numerical mathematics, and built-in offline failover.

---

## Architecture Overview

```mermaid
flowchart TD
    subgraph DataFeeds["Data Feeds"]
        G["NaxosData API Gateway"]
        K["Kalshi DCM Native API"]
        O["Offline Fallback Mock Cache"]
    end

    subgraph CoreSDK["Core SDK Runtime"]
        C["KalshiClient / AsyncKalshiClient"]
        M["Pydantic v2 Models: Market, OrderBook, Candlestick, Trade, Position"]
    end

    subgraph QuantEngines["Quantitative Engines"]
        F["CFTC Rule 40.2 Fee Engine"]
        Q["Quadratic Execution Solver"]
        IV["Black-Scholes Binary IV Inverter"]
        TS["Probability Term Structure & Hazard Rates"]
        SC["Spread Compression & Micro-Price"]
    end

    subgraph Applications["Applications"]
        CLI["kalshi-cli Console Suite"]
        BOT["Automated Arbitrage & Market Making Bots"]
        EXP["JSON / CSV Institutional Data Exporters"]
    end

    G --> C
    K --> C
    O -.->|Failover| C
    C --> M
    M --> F
    M --> Q
    M --> IV
    M --> TS
    M --> SC
    F --> CLI
    Q --> CLI
    IV --> CLI
    TS --> CLI
    SC --> CLI
    F --> BOT
    Q --> BOT
    IV --> BOT
    TS --> BOT
    SC --> BOT
    C --> EXP
```

---

## Key Features

- **Asynchronous & Synchronous Clients**: Native `httpx` async event-loop integration for high-frequency market making or simple synchronous scripting with automated connection pooling.
- **CFTC Rule 40.2 Compliance**: Exact implementation of the CFTC regulatory fee schedule, taking into account binary variance rounding, ceiling mechanics, maker rebates, and NFA transaction assessments.
- **Quadratic Execution Sizing**: Analytically closed-form quadratic solver trading off alpha capture against market impact slippage (Kyle's $\lambda$) and regulatory fee drag under hard capital and exchange order size constraints.
- **Derivatives Analytics**:
  - Closed-form and Newton-Raphson inversion of Black-Scholes cash-or-nothing digital options ($C = e^{-rT}\Phi(d_2)$).
  - Piecewise continuous hazard rate ($\lambda(t)$) term structure modeling with log-linear survival probability interpolation.
  - Micro-price estimation, quote depth imbalance, and spread compression ratio tracking.
- **Institutional Telemetry & Offline Fallback**: Automated fallback to high-fidelity simulated orderbooks and market states when running in offline backtests, sandboxes, or during gateway network disruptions.
- **Production CLI**: Inspect live/mock tickers, stream L2 orderbooks, optimize trade sizing, and export OHLCV/tick data to CSV/JSON.

---

## Installation

```bash
# Clone the open-source repository
git clone https://github.com/nexosdata/kalshi-python-sdk.git
cd kalshi-python-sdk

# Install in editable mode with development dependencies
pip install -e ".[dev]"
```

Requirements: Python 3.10+, `httpx >= 0.24.0`, and `pydantic >= 2.0.0`.

---

## Quickstart

### 1. Synchronous Market Data & Micro-Price Inspection

```python
from kalshi import KalshiClient

# Initialize client (uses NaxosData API Gateway or offline mock mode)
with KalshiClient() as client:
    # Fetch active prediction markets
    markets = client.get_markets(limit=5)
    for m in markets:
        print(f"[{m.ticker}] {m.title} | Bid: ${m.yes_bid:.2f} Ask: ${m.yes_ask:.2f}")

    # Inspect Level 2 orderbook ladder and fair micro-price
    ticker = "KXFEDRATE-26DEC"
    ob = client.get_orderbook(ticker)
    print(f"Spread: ${ob.spread:.4f} | Mid: ${ob.mid_price:.4f} | Micro-Price: ${ob.micro_price:.4f}")
```

### 2. High-Throughput Asynchronous Orderbook Streaming

```python
import asyncio
from kalshi import AsyncKalshiClient

async def monitor_markets():
    async with AsyncKalshiClient() as client:
        # Fetch orderbook asynchronously
        orderbook = await client.get_orderbook("KXFEDRATE-26DEC")
        print(f"Best YES Bid: {orderbook.best_yes_bid.quantity} @ ${orderbook.best_yes_bid.price:.2f}")
        print(f"Best YES Ask: {orderbook.best_yes_ask.quantity} @ ${orderbook.best_yes_ask.price:.2f}")

        # Compute spread compression metrics
        metrics = await client.get_spread_compression("KXFEDRATE-26DEC")
        if metrics:
            print(f"Depth Imbalance: {metrics.depth_imbalance:+.2f}")
            print(f"Kyle's Lambda: ${metrics.kyles_lambda:.6f} per contract")

asyncio.run(monitor_markets())
```

---

## CFTC Rule 40.2 Fee Schedule & Mathematical Derivation

Kalshi operates as a Designated Contract Market (DCM) subject to CFTC regulatory filings. Binary prediction contracts pay $\$1.00$ upon affirmative resolution or $\$0.00$ otherwise, with prices bounded in $P \in [0.01, 0.99]$.

### 1. Variance-Dependent Regulatory Fee Formula

The theoretical uncertainty of a Bernoulli event contract at probability $P$ is governed by its variance:

$$\sigma_B^2 = P(1 - P)$$

Under Kalshi's CFTC Rule 40.2 regulatory submission, taker transaction fees are directly proportional to this variance. The fee factor is established at $\gamma = 0.07$ (7%). For an order of $N$ contracts at price $P$, the exchange fee in dollars is:

$$\text{Exchange Fee}(N, P) = \frac{\lceil 100 \times N \times \gamma \times P \times (1 - P) \rceil}{100}$$

where $\lceil \cdot \rceil$ represents the ceiling function rounding upwards to the nearest integer cent per CFTC exchange rules.

Total regulatory transaction costs include the National Futures Association (NFA) assessment fee $c_{\text{nfa}} = \$0.0002$ per contract:

$$\text{Total Fee}(N, P) = \text{Exchange Fee}(N, P) + N \times c_{\text{nfa}}$$

### 2. Analytical Sensitivity & Marginal Fee Derivative

The sensitivity of the fee rate per contract with respect to price $P$ is given by the first derivative:

$$\frac{d}{dP} \left[ \gamma P (1 - P) \right] = \gamma (1 - 2P)$$

- For out-of-the-money or deep in-the-money contracts ($P < 0.50$ or $P > 0.50$), fee drag is minimized ($P = 0.01 \implies \text{fee} \approx \$0.000693$/contract).
- At maximum uncertainty ($P = 0.50$), $\frac{d\text{Fee}}{dP} = 0$, achieving maximum fee drag of $\$0.0175$/contract ($1.75$ cents).
- Symmetry: $\text{Fee}(P) = \text{Fee}(1 - P)$, ensuring unbiased neutrality between buying YES or NO.

### 3. Quantitative Quadratic Execution Solver

When deploying an alpha model with fair valuation $V \in (0, 1)$ against best market offer $P_0$, aggressive liquidity consumption causes market impact slippage modeled via linear orderbook depth slope $\lambda$:

$$P(q) = P_0 + \lambda q$$

Total execution cash outflow for $Q$ contracts:

$$C(Q) = \int_0^Q (P_0 + \lambda q) dq + Q \cdot \bar{f}(P_0) = \left(P_0 + \bar{f}(P_0)\right) Q + \frac{1}{2}\lambda Q^2$$

Expected payout: $E[\text{Payout}] = V \cdot Q$. The expected net profit objective function $\Pi(Q)$ is strictly concave quadratic:

$$\Pi(Q) = (V - P_0 - \bar{f}(P_0)) Q - \frac{1}{2}\lambda Q^2$$

Defining net edge $\mathcal{E} = V - P_0 - \bar{f}(P_0)$:
- If $\mathcal{E} \le 0$, the edge does not exceed regulatory fee drag $\implies Q^* = 0$.
- If $\mathcal{E} > 0$, the unconstrained First-Order Condition $\frac{d\Pi}{dQ} = 0$ yields:

$$Q^*_{\text{unconstrained}} = \frac{\mathcal{E}}{\lambda} = \frac{V - P_0 - \bar{f}(P_0)}{\lambda}$$

Subject to order limit $Q \le Q_{\max}$ and quadratic capital budget constraint $C(Q) \le B_{\max}$:

$$Q^*_{\text{budget}} = \frac{-(P_0 + \bar{f}) + \sqrt{(P_0 + \bar{f})^2 + 2\lambda B_{\max}}}{\lambda}$$

$$Q^* = \left\lfloor \min\left( Q^*_{\text{unconstrained}}, Q_{\max}, Q^*_{\text{budget}} \right) \right\rfloor$$

```python
from kalshi import solve_optimal_order_size

# Solve optimal trade size balancing alpha, CFTC fees, and Kyle's lambda
solution = solve_optimal_order_size(
    target_valuation=0.72,   # Proprietary model fair probability
    market_price=0.62,       # Current best ask
    depth_liquidity=15000,   # Available book contracts
    max_order_size=2500,     # Risk limit
    capital_budget=1500.0,   # $1,500 cash allocation
)

print(f"Optimal Contracts (Q*): {solution.optimal_contracts}")
print(f"Expected Net Profit:     ${solution.expected_net_profit:.2f}")
print(f"CFTC Fee Drag:          -${solution.estimated_cftc_fees:.2f}")
print(f"Binding Constraint:      {solution.binding_constraint}")
```

---

## Quantitative Analytics & Derivatives Engine

### 1. Black-Scholes Digital Option Implied Volatility Inversion

A Kalshi contract paying $\$1.00$ when underlying index $S_T \ge K$ represents a European cash-or-nothing binary call option:

$$C_{\text{binary}} = e^{-rT} \Phi(d_2)$$

where:

$$d_2 = \frac{\ln(S / K) + \left(r - \frac{1}{2}\sigma^2\right)T}{\sigma \sqrt{T}}$$

Given observed market price $P$, we solve for annualized implied volatility $\sigma$ by inverting $d_2 = \Phi^{-1}(P e^{rT}) = z$. This reduces to the quadratic equation:

$$\frac{1}{2} T \sigma^2 + z \sqrt{T} \sigma - \left(\ln(S / K) + r T\right) = 0$$

$$\sigma^* = \frac{-z \sqrt{T} + \sqrt{z^2 T + 2 T (\ln(S/K) + rT)}}{T}$$

```python
from kalshi import calculate_implied_volatility

res = calculate_implied_volatility(
    contract_price=0.50,     # Binary call price ($0.50)
    spot=100.0,              # Current index / asset price
    strike=100.0,            # Strike price
    time_to_expiry=0.25,     # 3 months (0.25 years)
    risk_free_rate=0.05,     # 5.0% risk-free yield
)

print(f"Implied Volatility: {res.implied_volatility * 100:.2f}% | d2: {res.d2:.4f}")
```

### 2. Probability Term Structure & Hazard Rates

Prediction market contracts with sequential maturities $T_1 < T_2 < \dots < T_n$ define a cumulative probability curve $P(t)$. The survival probability $S(t) = 1 - P(t)$ is parameterized by continuous hazard rates $\lambda(t)$:

$$S(T_{i+1}) = S(T_i) \exp\left( -\bar{\lambda}_{i, i+1} (T_{i+1} - T_i) \right) \implies \bar{\lambda}_{i, i+1} = -\frac{\ln S(T_{i+1}) - \ln S(T_i)}{T_{i+1} - T_i}$$

```python
from kalshi import ProbabilityTermStructure

points = [(14.0, 0.22), (30.0, 0.35), (60.0, 0.52), (90.0, 0.65), (180.0, 0.81)]
term_structure = ProbabilityTermStructure(points=points)

# Interpolate probability at an unlisted intermediate horizon (e.g., 45 days)
prob_45d = term_structure.interpolate_probability(45.0)
print(f"Interpolated 45-day Event Probability: {prob_45d * 100:.2f}%")
```

### 3. Spread Compression & Micro-Price Fair Value

The volume-weighted micro-price accounts for bid-ask queue imbalance:

$$P_{\text{micro}} = \frac{Q_{\text{bid}} P_{\text{ask}} + Q_{\text{ask}} P_{\text{bid}}}{Q_{\text{bid}} + Q_{\text{ask}}}$$

The Spread Compression Index (SCI) tracks the degree to which maker competition has compressed the spread toward the exchange tick minimum ($\$0.01$):

$$\text{SCI} = \frac{\$0.01}{\max(\$0.01, P_{\text{ask}} - P_{\text{bid}})} \in (0, 1.0]$$

```python
from kalshi import analyze_spread_compression, OrderBook, OrderBookLevel

ob = OrderBook(
    ticker="KXFEDRATE-26DEC",
    yes_bids=[OrderBookLevel(price=0.62, quantity=15000)],
    yes_asks=[OrderBookLevel(price=0.63, quantity=5000)],
)
metrics = analyze_spread_compression(ob)
print(f"Micro-Price:        ${metrics.micro_price:.4f}")
print(f"Depth Imbalance:    {metrics.depth_imbalance:+.2f}")
print(f"Compression Index:  {metrics.compression_index:.2f} (1.0 = minimum tick)")
```

---

## Command Line Interface (CLI)

The SDK provides `kalshi-cli` (and alias `kalshi-sdk`):

```bash
# List active prediction markets
kalshi-cli markets --limit 5

# View detailed market specifications and quotes
kalshi-cli ticker KXFEDRATE-26DEC

# Inspect Level 2 orderbook ladder and micro-price
kalshi-cli orderbook KXFEDRATE-26DEC --depth 5

# Compute exact CFTC Rule 40.2 fees for an order
kalshi-cli fee --contracts 500 --price 0.62

# Run quantitative quadratic sizing solver
kalshi-cli optimize --target 0.72 --price 0.62 --depth 15000 --max-contracts 2500

# Calculate Black-Scholes binary implied volatility
kalshi-cli analytics --calc-iv --price 0.50 --spot 100 --strike 100 --time 0.25

# Display probability term structure and hazard rates
kalshi-cli analytics --term-structure

# Export market orderbook or candlesticks to JSON or CSV
kalshi-cli export --ticker KXFEDRATE-26DEC --data-type orderbook --format json --output book.json
kalshi-cli export --ticker KXFEDRATE-26DEC --data-type candlesticks --format csv --output ohlcv.csv
```

---

## NaxosData API Gateway & Telemetry

The SDK integrates seamlessly with the [NaxosData API Gateway](https://api.naxosdata.com), providing an institutional aggregation layer for cross-venue prediction market routing:

| Endpoint | Method | Description |
| :--- | :--- | :--- |
| `/api/v1/markets?venue=KALSHI` | `GET` | Filterable directory of all active Kalshi event contracts |
| `/api/v1/markets/{ticker}?venue=KALSHI` | `GET` | Real-time quote, volume, and settlement criteria |
| `/api/v1/orderbooks/KALSHI/{ticker}` | `GET` | Snapshot of Level 2 bids and asks |
| `/api/v1/candlesticks/KALSHI/{ticker}` | `GET` | Historical OHLCV aggregation bars (`1m`, `5m`, `1h`, `1d`) |
| `/api/v1/trades/KALSHI/{ticker}` | `GET` | Executed trade prints with aggressor side tagging |
| `/api/v1/positions?venue=KALSHI` | `GET` | Account portfolio positions and unrealized/realized PnL |
| `/api/v1/settlements/KALSHI/{ticker}` | `GET` | Official determination notices and payout reconciliations |

### Offline Mode & Graceful Degradation
To enable hermetic offline backtesting and CI/CD validation without network dependencies, instantiate the client with `offline_mode=True` or rely on automated failover when gateway connections encounter network timeouts.

---

## Running the Automated Test Suite

The test suite covers model validation, HTTP dispatch, CFTC fee math, quadratic solvers, analytics, and CLI commands:

```bash
# Execute full unit test suite with 100% pass rate
python3 -m unittest discover tests -v
```

All 59 unit tests execute in under 0.1 seconds without external mocking dependencies.

---

## License

This project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for complete details.

Copyright (c) 2026 NaxosData Contributors & William Gonda.
