stakepd.kalshi_data gets data from the Kalshi prediction market as pandas DataFrames, ready for analysis.It wraps the Kalshi Trade API v2 and deals with authentication, pagination, retries and type conversion, so you can work with the data straight away.
from stakepd import kalshi_data as kd
client = kd.KalshiClient()
markets = client.get_markets(status="open", series_ticker="KXHIGHNY")
datetime64.Method index:
Installation#
kalshi_data needs two packages on top of stakepd’s own: requests for HTTP and cryptography for signing requests. Install them with the kalshi extra:
Terminal:
pip install "stakepd[kalshi]"
Jupyter:
%pip install "stakepd[kalshi]"
In a Jupyter notebook, use %pip so the package goes into the notebook’s own Python.
stakepd doesn’t load the Kalshi module. It loads only when you import stakepd.kalshi_data.Quickstart#
import pandas as pd
from stakepd import kalshi_data as kd
client = kd.KalshiClient() # market data is public: no API key needed
# 1. Find markets: today's NYC high-temperature brackets
markets = client.get_markets(status="open", series_ticker="KXHIGHNY")
print(markets[["ticker", "yes_sub_title", "yes_bid", "yes_ask", "volume"]])
# 2. Price history for the most-traded bracket
ticker = markets.sort_values("volume", ascending=False).iloc[0]["ticker"]
candles = client.get_candlesticks(ticker, start="2026-11-26", interval="1h")
candles["price_close"].plot(title=ticker)
# 3. Recent trades
trades = client.get_trades(ticker, max_results=500)
# 4. Your own account (needs an API key, see "Authentication")
me = kd.KalshiClient.from_env()
positions = me.get_positions()
Key concepts#
Series, events and markets#
Kalshi organises contracts in three levels:
"Highest temperature in NYC" (daily)KXHIGHNY
"Highest temperature in NYC on Nov 27"KXHIGHNY-26NOV27
"57ยฐ to 58ยฐ"KXHIGHNY-26NOV27-B57.5
Each market is a binary contract that pays $1 if it resolves YES and $0 otherwise. In many events, such as temperature brackets, the markets are mutually exclusive: exactly one of them resolves YES.
Typical ways to drill down:
client.get_series_list(category="Climate and Weather") # find series
client.get_events(series_ticker="KXHIGHNY") # events in a series
client.get_markets(event_ticker="KXHIGHNY-26NOV27") # markets in an event
How the data is shaped#
Every method returns either a DataFrame or a Series, except two that return a plain dict (get_exchange_status, get_balance). The wrapper applies these conventions everywhere:
| Convention | Details |
|---|---|
| Prices are float dollars | Between 0.00 and 1.00. Because a contract pays $1, a price is also the market’s implied probability of YES: yes_ask = 0.71 means roughly a 71% chance. |
| Contract counts are float | Kalshi allows fractional contracts, so volume, count, position and similar columns can hold values like 18.46. |
| Simpler column names | Kalshi’s _dollars and _fp suffixes are dropped: yes_bid_dollars becomes yes_bid, and volume_fp becomes volume. If removing a suffix would clash with an existing column, the original name is kept. |
Times are UTC datetime64 | Columns ending in _time, _date, _datetime or _ts become timezone-aware datetime64[ns, UTC]. Use .dt.tz_convert("America/New_York") for local time. |
| One unit for money | The few fields Kalshi sends in cents (balance, portfolio_value, settlement revenue and value) are converted to dollars. |
| Key columns first | Identifying columns (ticker, prices, volumeโฆ) come first, followed by every other field Kalshi returns. |
| Empty results keep their columns | A query with no matches returns an empty DataFrame that still has the main columns, so df["ticker"] works either way. |
| Nested fields are kept as-is | Fields like price_ranges or product_metadata stay as Python lists or dicts in a single column. |
Time arguments#
Every time argument (start, end, min_close, โฆ) accepts any of these:
| Type | Example |
|---|---|
str | "2026-11-01", "2026-11-01 14:30", "2026-11-01T14:30:00-05:00" |
datetime.datetime / datetime.date | datetime(2026, 11, 1, 14, 30), date(2026, 11, 1) |
pandas.Timestamp | pd.Timestamp("2026-11-01", tz="US/Eastern"), pd.Timestamp.now(tz="UTC") - pd.Timedelta(days=7) |
int / float | Unix seconds, e.g. 1793577600 |
Times without a timezone are treated as UTC.
1793577600000) raises a ValueError rather than silently asking for the wrong date.Pagination and max_results#
Kalshi returns long lists in pages. Every list method follows the pages for you and returns one combined DataFrame.
max_results=None(the default) fetches everything that matches.max_results=500stops after 500 rows, and requests no more pages than it needs.
Some queries match a lot of rows: for example get_markets() with no filters, or get_trades() without a ticker or time window. For those, set max_results or add a filter.
Authentication#
Market data is public. Portfolio data (balance, positions, fills, orders, settlements) needs a Kalshi API key, which has two parts:
- API key ID: a string like
a1b2c3d4-.... - Private key: a
.pemfile you download once when you create the key.
Create a key at kalshi.com โ Account & security โ API Keys (Kalshi’s guide). Both RSA and Ed25519 keys are supported.
.pem file private: never commit it to git or paste it into a notebook you share.Option A: pass the credentials directly
client = kd.KalshiClient(
api_key_id="a1b2c3d4-...",
private_key_path="~/.kalshi/kalshi_private_key.pem",
)
Option B: environment variables (recommended)
Add these to ~/.zshrc (or your shell’s profile):
export KALSHI_API_KEY_ID="a1b2c3d4-..."
export KALSHI_PRIVATE_KEY_PATH="$HOME/.kalshi/kalshi_private_key.pem"
Then, in Python:
client = kd.KalshiClient.from_env()
The client signs every request with your key, as Kalshi requires. You never handle signatures yourself.
demo = kd.KalshiClient.from_env(environment="demo")
Client#
KalshiClient#
kd.KalshiClient(api_key_id=None, private_key=None, private_key_path=None, *,
environment="prod", base_url=None, timeout=30.0, max_retries=3, session=None)
Creates a client. Without credentials, the client can fetch every market-data endpoint. With credentials, it can also fetch portfolio data.
Parameters:
api_key_id(str, optional): Your Kalshi API key ID.private_key(strorbytes, optional): The private key’s PEM text. Use this orprivate_key_path, not both.private_key_path(stroros.PathLike, optional): Path to the private key.pemfile.~is expanded.environment(str, optional):"prod"(default) or"demo".base_url(str, optional): A custom API base URL. Overridesenvironment.timeout(float, optional): Seconds to wait for each HTTP response. Default30.0.max_retries(int, optional): How many times to retry a request that gets a rate-limit (429) or server (5xx) error, with exponential backoff. Default3.session(requests.Session, optional): Use your own HTTP session, for example to add a proxy or for testing. By default, the client builds one with retries.
Returns:
KalshiClient
Raises:
KalshiAuthError: if only one ofapi_key_idand a private key is given, or the key file can’t be read or parsed.ValueError: ifenvironmentis not"prod"or"demo".
Attributes and other methods:
client.is_authenticated(bool):Trueif the client has credentials.client.base_url(str): The API URL in use.client.close(): Closes the HTTP session. You can also use the client as a context manager:
with kd.KalshiClient() as client:
markets = client.get_markets(status="open", max_results=100)
Example:
client = kd.KalshiClient()
print(client)
Output:
KalshiClient(base_url='https://external-api.kalshi.com/trade-api/v2', authenticated=False)
KalshiClient.from_env#
kd.KalshiClient.from_env(**kwargs)
Creates an authenticated client from environment variables. It reads KALSHI_API_KEY_ID, plus either KALSHI_PRIVATE_KEY_PATH (path to the .pem file) or KALSHI_PRIVATE_KEY (the PEM text itself).
Parameters:
**kwargs: Passed to theKalshiClientconstructor, e.g.environment="demo"ortimeout=60.
Returns:
KalshiClient: an authenticated client.
Raises:
KalshiAuthError: if the environment variables are not set.
Example:
client = kd.KalshiClient.from_env()
print(client.is_authenticated)
Output:
True
Market data#
These methods work with or without an API key.
get_markets#
client.get_markets(*, status=None, event_ticker=None, series_ticker=None, tickers=None,
min_close=None, max_close=None, min_settled=None, max_settled=None,
max_results=None, **filters)
Lists markets, one row per market. This is the usual starting point for finding contracts to analyse.
Parameters:
status(str, optional):"unopened","open","paused","closed"or"settled".event_ticker(str, optional): Only markets in this event, e.g."KXHIGHNY-26NOV27".series_ticker(str, optional): Only markets in this series, e.g."KXHIGHNY".tickers(strorlist[str], optional): Only these market tickers.min_close,max_close(time, optional): Only markets that close within this window.min_settled,max_settled(time, optional): Only markets that settled within this window.max_results(int, optional): Stop after this many markets.Nonefetches all of them.**filters: Any other Kalshi query parameter, passed through unchanged. For example,mve_filter="exclude"leaves out multi-leg “combo” markets.
Returns:
pandas.DataFrame: one row per market. Main columns:
| Column | Type | Description |
|---|---|---|
ticker | str | Market ticker |
event_ticker | str | Parent event |
status | str | active, closed, determined, finalized, โฆ (Kalshi’s internal status names, which differ from the status filter values) |
yes_sub_title | str | What YES means, e.g. "57ยฐ to 58ยฐ" |
yes_bid, yes_ask | float | Best bid and ask for YES, in dollars (= implied probability) |
no_bid, no_ask | float | Best bid and ask for NO |
last_price | float | Price of the most recent trade |
volume, volume_24h | float | Contracts traded, all time and over the last 24 hours |
open_interest | float | Contracts currently held |
open_time, close_time | datetime64[ns, UTC] | When trading opens and closes |
result | str | "yes" / "no" once settled, empty before |
Every other field Kalshi returns is included too, such as rules_primary, previous_price, yes_bid_size, created_time, price_ranges and market_type.
Example:
markets = client.get_markets(status="open", series_ticker="KXHIGHNY")
print(markets[["ticker", "yes_sub_title", "yes_bid", "yes_ask", "volume", "close_time"]].head(4))
Output:
ticker yes_sub_title yes_bid yes_ask volume close_time
0 KXHIGHNY-26NOV27-T64 65ยฐ or above 0.00 0.01 182.00 2026-11-28 06:00:00+00:00
1 KXHIGHNY-26NOV27-T57 56ยฐ or below 0.29 0.31 11083.45 2026-11-28 06:00:00+00:00
2 KXHIGHNY-26NOV27-B63.5 63ยฐ to 64ยฐ 0.00 0.01 502.00 2026-11-28 06:00:00+00:00
3 KXHIGHNY-26NOV27-B61.5 61ยฐ to 62ยฐ 0.00 0.01 753.00 2026-11-28 06:00:00+00:00
More examples:
# Markets closing in the next 24 hours
now = pd.Timestamp.now(tz="UTC")
closing_soon = client.get_markets(status="open", min_close=now, max_close=now + pd.Timedelta(hours=24))
# Specific markets
client.get_markets(tickers=["KXHIGHNY-26NOV27-B57.5", "KXHIGHNY-26NOV27-T57"])
# Everything that settled last week
settled = client.get_markets(status="settled", min_settled="2026-11-16", max_settled="2026-11-23")
get_market#
client.get_market(ticker)
Gets one market.
Parameters:
ticker(str): Market ticker.
Returns:
pandas.Series: indexed by field name, with the same fields as aget_marketsrow. Its.nameis the ticker.
Raises:
KalshiAPIError: withstatus_code == 404if the market doesn’t exist.
Example:
m = client.get_market("KXHIGHNY-26NOV27-B57.5")
print(m[["event_ticker", "status", "yes_sub_title", "yes_bid", "yes_ask", "last_price", "volume", "close_time"]])
Output:
event_ticker KXHIGHNY-26NOV27
status active
yes_sub_title 57ยฐ to 58ยฐ
yes_bid 0.7
yes_ask 0.71
last_price 0.71
volume 12849.67
close_time 2026-11-28 06:00:00+00:00
Name: KXHIGHNY-26NOV27-B57.5, dtype: object
get_orderbook#
client.get_orderbook(ticker, depth=None)
Gets the current order book for a market, in long format.
Kalshi lists bids only, for both YES and NO. A NO bid at price p is the same as a YES ask at 1 - p, so:
- best YES ask =
1 - best NO bid - best NO ask =
1 - best YES bid
Parameters:
ticker(str): Market ticker.depth(int, optional): Return only the best N price levels on each side (1โ100).Nonereturns the whole book.
Returns:
pandas.DataFrame, with each side sorted best price first:
| Column | Type | Description |
|---|---|---|
side | str | "yes" or "no" |
price | float | Bid price in dollars |
quantity | float | Contracts bid at that price |
Raises:
ValueError: ifdepthis outside 1โ100.
Example:
book = client.get_orderbook("KXHIGHNY-26NOV27-B57.5", depth=3)
print(book)
Output:
side price quantity
0 yes 0.70 345.44
1 yes 0.69 2.00
2 yes 0.68 83.81
3 no 0.29 109.00
4 no 0.28 46.80
5 no 0.27 41.00
The best YES bid is 0.70, and the best YES ask is 1 โ 0.29 = 0.71.
yes = book[book.side == "yes"]
no = book[book.side == "no"]
best_bid, best_ask = yes.price.max(), 1 - no.price.max()
spread = best_ask - best_bid # 0.01
get_trades#
client.get_trades(ticker=None, *, start=None, end=None, max_results=None)
Lists public trades (every matched trade on the exchange, not just yours), newest first.
Parameters:
ticker(str, optional): Only trades in this market.Nonereturns trades across all markets.start,end(time, optional): Only trades within this window.max_results(int, optional): Stop after this many trades. Without atickeror time window, set this: there can be millions of trades.
Returns:
pandas.DataFrame: one row per trade.
| Column | Type | Description |
|---|---|---|
trade_id | str | Unique trade ID |
ticker | str | Market ticker |
created_time | datetime64[ns, UTC] | When the trade happened |
yes_price, no_price | float | Trade price for each side (they add up to 1) |
count | float | Contracts traded |
taker_outcome_side | str | "yes" or "no": the side the aggressor (taker) bought |
taker_book_side | str | "bid" or "ask" |
Example:
trades = client.get_trades("KXHIGHNY-26NOV27-B57.5", max_results=4)
print(trades[["created_time", "yes_price", "no_price", "count", "taker_outcome_side"]])
Output:
created_time yes_price no_price count taker_outcome_side
0 2026-11-27 07:09:33.402301+00:00 0.71 0.29 5.00 yes
1 2026-11-27 07:08:36.563541+00:00 0.70 0.30 40.00 no
2 2026-11-27 07:07:19.752408+00:00 0.70 0.30 18.46 no
3 2026-11-27 07:06:14.298487+00:00 0.70 0.30 15.38 no
More examples:
# All trades in a market over one day
day = client.get_trades("KXHIGHNY-26NOV27-B57.5", start="2026-11-26", end="2026-11-27")
# Volume-weighted average price (VWAP)
vwap = (day.yes_price * day["count"]).sum() / day["count"].sum()
# Contracts traded per 15 minutes
day.set_index("created_time")["count"].resample("15min").sum()
count is also the name of a DataFrame method, so write df["count"] rather than df.count.get_candlesticks#
client.get_candlesticks(ticker, start, end=None, *, interval="1h", series_ticker=None)
Gets OHLC price history for a market as a time-indexed DataFrame, ready to plot or resample.
Kalshi allows at most 5,000 candles per request. Longer ranges are split into several requests and joined automatically. For example, a month of 1-minute candles takes about 9 requests.
Parameters:
ticker(str): Market ticker.start(time): Start of the range.end(time, optional): End of the range. Defaults to now.interval(strorint, optional): Candle length:"1m","1h"(default) or"1d". The equivalent minutes1,60and1440also work.series_ticker(str, optional): The market’s series ticker. If you leave it out, it’s looked up for you, which costs two extra requests. Pass it when you fetch many markets from the same series.
Returns:
pandas.DataFrame, indexed byend_period_ts(a UTCDatetimeIndex, the end of each candle) and sorted oldest first:
| Column | Type | Description |
|---|---|---|
price_open, price_high, price_low, price_close | float | OHLC of traded prices. NaN in candles with no trades. |
price_mean | float | Mean traded price within the candle |
price_previous | float | Last traded price before this candle |
yes_bid_open, yes_bid_high, yes_bid_low, yes_bid_close | float | OHLC of the best YES bid (quoted, so defined even without trades) |
yes_ask_open, yes_ask_high, yes_ask_low, yes_ask_close | float | OHLC of the best YES ask |
volume | float | Contracts traded in the candle |
open_interest | float | Open interest at the end of the candle |
Raises:
ValueError: ifintervalisn’t recognised, orstartisn’t beforeend.
Example:
candles = client.get_candlesticks("KXHIGHNY-26NOV27-B57.5", start="2026-11-26",
interval="1h", series_ticker="KXHIGHNY")
print(candles[["price_open", "price_high", "price_low", "price_close", "volume"]].dropna().tail(4))
Output:
price_open price_high price_low price_close volume
end_period_ts
2026-11-27 04:00:00+00:00 0.30 0.69 0.30 0.50 3198.40
2026-11-27 05:00:00+00:00 0.51 0.57 0.51 0.57 594.85
2026-11-27 06:00:00+00:00 0.57 0.77 0.57 0.74 3850.81
2026-11-27 07:00:00+00:00 0.74 0.76 0.70 0.72 2390.41
More examples:
# Plot the probability over time
candles["price_close"].ffill().plot(ylabel="P(YES)")
# Mid-price is defined even when nothing traded
candles["mid"] = (candles.yes_bid_close + candles.yes_ask_close) / 2
# Convert to New York time
candles.index = candles.index.tz_convert("America/New_York")
# Downsample 1-minute candles to 5-minute candles
m1 = client.get_candlesticks(ticker, start="2026-11-26", interval="1m", series_ticker="KXHIGHNY")
m5 = m1.resample("5min").agg({"price_open": "first", "price_high": "max",
"price_low": "min", "price_close": "last", "volume": "sum"})
get_events#
client.get_events(*, status=None, series_ticker=None, tickers=None, min_close=None,
max_results=None, **filters)
Lists events, one row per event.
Parameters:
status(str, optional):"unopened","open","closed"or"settled".series_ticker(str, optional): Only events in this series.tickers(strorlist[str], optional): Only these event tickers.min_close(time, optional): Only events with at least one market closing after this time.max_results(int, optional): Stop after this many events.**filters: Any other Kalshi query parameter, passed through unchanged.
Returns:
pandas.DataFrame: one row per event.
| Column | Type | Description |
|---|---|---|
event_ticker | str | Event ticker |
series_ticker | str | Parent series |
title | str | Event title |
sub_title | str | Subtitle (often the date) |
mutually_exclusive | bool | True if at most one market in the event can resolve YES |
strike_date | datetime64[ns, UTC] | When the event’s outcome is determined |
Example:
events = client.get_events(series_ticker="KXHIGHNY", max_results=3)
print(events[["event_ticker", "title", "strike_date"]])
Output:
event_ticker title strike_date
0 KXHIGHNY-26NOV27 Highest temperature in New York City on Nov 27... 2026-11-28 06:00:00+00:00
1 KXHIGHNY-26NOV26 Highest temperature in New York City on Nov 26... 2026-11-27 06:00:00+00:00
2 KXHIGHNY-26NOV25 Highest temperature in New York City on Nov 25... 2026-11-26 06:00:00+00:00
get_event#
client.get_event(event_ticker)
Gets one event. To get its markets, use client.get_markets(event_ticker=...).
Parameters:
event_ticker(str): Event ticker.
Returns:
pandas.Series: the same fields as aget_eventsrow.
Example:
event = client.get_event("KXHIGHNY-26NOV27")
print(event[["series_ticker", "title", "mutually_exclusive"]])
Output:
series_ticker KXHIGHNY
title Highest temperature in New York City on Nov 27...
mutually_exclusive True
Name: KXHIGHNY-26NOV27, dtype: object
get_series_list#
client.get_series_list(*, category=None, tags=None, include_volume=False)
Lists series. Use it to discover what Kalshi offers. Kalshi returns this list in a single response, with no paging.
Parameters:
category(str, optional): Only series in this category. It’s exact and case-sensitive: e.g."Sports","Politics","Elections","Economics","Financials","Crypto","Climate and Weather","Entertainment".get_series_list()["category"].unique()lists them all.tags(strorlist[str], optional): Only series with these tags.include_volume(bool, optional): Add avolumecolumn with the total contracts traded. DefaultFalse.
Returns:
pandas.DataFrame: one row per series. Main columns:ticker,title,category,frequency("daily","weekly","monthly","annual","one_off","custom") andtags.
Example:
series = client.get_series_list()
print(series.shape)
print(series["category"].value_counts().head())
weather = client.get_series_list(category="Climate and Weather", include_volume=True)
weather.nlargest(5, "volume")[["ticker", "title", "volume"]]
get_series#
client.get_series(series_ticker)
Gets one series.
Parameters:
series_ticker(str): Series ticker.
Returns:
pandas.Series: the same fields as aget_series_listrow.
Example:
print(client.get_series("KXHIGHNY")[["title", "category", "frequency"]])
Output:
title Highest temperature in NYC
category Climate and Weather
frequency daily
Name: KXHIGHNY, dtype: object
get_series_ticker_for_market#
client.get_series_ticker_for_market(ticker)
Looks up which series a market belongs to. get_candlesticks uses this when you don’t pass series_ticker.
Parameters:
ticker(str): Market ticker.
Returns:
str: the series ticker, e.g."KXHIGHNY".
get_exchange_status#
client.get_exchange_status()
Checks whether the exchange is open and trading.
Returns:
dict: includesexchange_active(bool),trading_active(bool) andexchange_estimated_resume_time(strorNone).
Example:
status = client.get_exchange_status()
print(status["exchange_active"], status["trading_active"])
Output:
True True
Portfolio data#
These methods need an authenticated client (see Authentication).
KalshiAuthError before any request is sent.get_balance#
client.get_balance()
Gets your account balance.
Returns:
dict:
| Key | Type | Description |
|---|---|---|
balance | float | Cash available, in dollars |
portfolio_value | float | Current value of your open positions, in dollars |
updated_ts | pandas.Timestamp | When the balance was last updated (UTC) |
Example:
client.get_balance()
Output (illustrative values):
{'balance': 123.45, 'portfolio_value': 50.0, 'updated_ts': Timestamp('2026-11-27 10:00:00+0000', tz='UTC')}
get_positions#
client.get_positions(*, ticker=None, event_ticker=None, settlement_status="unsettled",
count_filter=None, max_results=None)
Lists your positions, one row per market.
Parameters:
ticker(str, optional): Only this market.event_ticker(str, optional): Only markets in this event.settlement_status(str, optional):"unsettled"(default, i.e. open positions),"settled"or"all".count_filter(strorlist[str], optional):"position"and/or"total_traded". Leaves out rows where that value is zero. For example,count_filter="position"hides markets you’ve fully exited.max_results(int, optional): Stop after this many rows.
Returns:
pandas.DataFrame: one row per market.
| Column | Type | Description |
|---|---|---|
ticker | str | Market ticker |
position | float | Contracts held. Positive = YES, negative = NO. |
market_exposure | float | Cost basis of the current position, in dollars |
realized_pnl | float | Realised profit or loss, in dollars |
fees_paid | float | Fees paid, in dollars |
total_traded | float | Total dollars traded in this market |
last_updated_ts | datetime64[ns, UTC] | Last change to the position |
Example:
pos = client.get_positions(count_filter="position")
pos["side"] = pos.position.gt(0).map({True: "YES", False: "NO"})
print(pos[["ticker", "side", "position", "market_exposure", "realized_pnl"]])
get_event_positions#
client.get_event_positions(*, event_ticker=None, settlement_status="unsettled",
count_filter=None, max_results=None)
Lists your positions added up per event.
Parameters:
- The same as
get_positions, withoutticker.
Returns:
pandas.DataFrame: one row per event, with columnsevent_ticker,total_cost,total_cost_shares,event_exposure,realized_pnlandfees_paid(allfloatdollars except the ticker andtotal_cost_shares, which is a contract count).
get_fills#
client.get_fills(*, ticker=None, order_id=None, start=None, end=None, max_results=None)
Lists your fills, newest first. A fill is one execution of one of your orders, and an order can fill in several pieces.
Parameters:
ticker(strorlist[str], optional): Only these markets (up to 100).order_id(str, optional): Only fills of this order.start,end(time, optional): Only fills within this window.max_results(int, optional): Stop after this many fills.
Returns:
pandas.DataFrame: one row per fill.
| Column | Type | Description |
|---|---|---|
fill_id | str | Unique fill ID |
order_id | str | The order that filled |
ticker | str | Market ticker |
created_time | datetime64[ns, UTC] | When it filled |
outcome_side | str | "yes" or "no" |
book_side | str | "bid" (you bought) or "ask" (you sold) |
count | float | Contracts filled |
yes_price, no_price | float | Fill price for each side, in dollars |
is_taker | bool | True if your order took liquidity |
fee_cost | float | Fee for this fill, in dollars |
Example:
fills = client.get_fills(start="2026-11-01")
fills["notional"] = fills["count"] * fills.yes_price.where(fills.outcome_side == "yes", fills.no_price)
daily = fills.set_index("created_time").resample("D")[["notional", "fee_cost"]].sum()
get_orders#
client.get_orders(*, ticker=None, event_ticker=None, status=None, start=None, end=None,
max_results=None)
Lists your orders, newest first.
Parameters:
ticker(str, optional): Only orders in this market.event_ticker(strorlist[str], optional): Only orders in these events (up to 100).status(str, optional):"resting"(still open on the book),"canceled"or"executed".start,end(time, optional): Only orders created within this window.max_results(int, optional): Stop after this many orders.
Returns:
pandas.DataFrame: one row per order.
| Column | Type | Description |
|---|---|---|
order_id | str | Order ID |
ticker | str | Market ticker |
status | str | resting, canceled or executed |
created_time | datetime64[ns, UTC] | When the order was placed |
outcome_side, book_side | str | Which side, and buy (bid) or sell (ask) |
type | str | limit or market |
yes_price, no_price | float | Limit price for each side |
initial_count, fill_count, remaining_count | float | Contracts ordered, filled and still open |
Other fields include expiration_time, taker_fees, maker_fees and client_order_id.
Example:
open_orders = client.get_orders(status="resting")
open_orders[["ticker", "outcome_side", "yes_price", "remaining_count"]]
get_settlements#
client.get_settlements(*, ticker=None, event_ticker=None, start=None, end=None,
max_results=None)
Lists markets you held when they settled, and what they paid out.
Parameters:
ticker(str, optional): Only this market.event_ticker(str, optional): Only markets in this event.start,end(time, optional): Only settlements within this window.max_results(int, optional): Stop after this many settlements.
Returns:
pandas.DataFrame: one row per settled market.
| Column | Type | Description |
|---|---|---|
ticker, event_ticker | str | Market and event |
settled_time | datetime64[ns, UTC] | When it settled |
market_result | str | "yes", "no" or "scalar" |
yes_count, no_count | float | Contracts you held on each side |
yes_total_cost, no_total_cost | float | What you paid for them, in dollars |
revenue | float | Payout, in dollars (Kalshi sends cents; converted) |
value | float | Settlement value per contract, in dollars (converted from cents) |
fee_cost | float | Fees, in dollars |
Example (profit and loss per settled market):
s = client.get_settlements()
s["pnl"] = s.revenue - s.yes_total_cost - s.no_total_cost - s.fee_cost
print(s[["ticker", "market_result", "pnl"]].sort_values("pnl"))
print("Total P&L:", round(s.pnl.sum(), 2))
Utilities#
These are also exported from stakepd.kalshi_data:
| Name | Description |
|---|---|
kd.to_unix_seconds(value, name="value") | Converts any time argument to int Unix seconds. Returns None for None. |
kd.load_private_key(private_key=None, private_key_path=None, password=None) | Loads an RSA or Ed25519 PEM private key. Raises KalshiAuthError if it can’t. |
kd.KalshiAuth(api_key_id, private_key) | A requests authentication handler that adds Kalshi’s signature headers. Useful for calling endpoints the wrapper doesn’t cover, with plain requests. |
kd.BASE_URLS | {"prod": ..., "demo": ...}: the API base URLs. |
Example:
import requests
auth = kd.KalshiAuth("a1b2c3d4-...", kd.load_private_key(private_key_path="~/.kalshi/key.pem"))
r = requests.get(kd.BASE_URLS["prod"] + "/portfolio/balance", auth=auth)
Errors#
All exceptions inherit from kd.KalshiError, so except kd.KalshiError catches everything raised by this module.
| Exception | Raised when |
|---|---|
kd.KalshiAuthError | Credentials are missing, incomplete or unreadable, or a portfolio method is called on a client without credentials. |
kd.KalshiAPIError | Kalshi returns an HTTP error, e.g. 404 for an unknown market or 401 for a bad key. Has .status_code, .code, .message, .details and .url. |
ValueError | An argument is invalid, such as an unknown status, a bad interval, a millisecond timestamp, or max_results=0. |
Rate-limit (429) and server (5xx) errors are retried automatically with exponential backoff, up to max_retries times, before a KalshiAPIError is raised.
try:
m = client.get_market("NOT-A-REAL-TICKER")
except kd.KalshiAPIError as e:
print(e.status_code, e.code, e.message)
Recipes#
Implied probabilities and stakepd odds functions#
Kalshi prices are implied probabilities, so they work directly with the rest of stakepd:
import stakepd as spd
m = client.get_markets(event_ticker="KXHIGHNY-26NOV27")
m = m[m.yes_ask > 0]
m["american"] = m.yes_ask.odds(odds_type="american") # price โ American odds
m["decimal"] = m.yes_ask.odds(odds_type="decimal") # price โ decimal odds
Overround of a mutually exclusive event#
If exactly one bracket resolves YES, the YES asks should add up to about 1. Anything above 1 is the market’s overround, and devig gives the fair probabilities:
asks = m.set_index("yes_sub_title").yes_ask
print("Overround:", asks.overround()) # e.g. 0.03 = 3%
fair = asks.devig() # probabilities rescaled to sum to 1
Price history for every market in an event#
markets = client.get_markets(event_ticker="KXHIGHNY-26NOV27")
closes = pd.DataFrame({
row.yes_sub_title: client.get_candlesticks(row.ticker, start="2026-11-25", interval="1h",
series_ticker="KXHIGHNY")["price_close"]
for row in markets.itertuples()
}).ffill()
closes.plot(ylabel="P(YES)")
Scan for the most active markets right now#
open_mkts = client.get_markets(status="open", mve_filter="exclude")
open_mkts["spread"] = open_mkts.yes_ask - open_mkts.yes_bid
top = open_mkts.nlargest(20, "volume_24h")[["ticker", "yes_sub_title", "yes_bid", "yes_ask", "spread", "volume_24h"]]
Calibration: how well do prices predict outcomes?#
This recipe takes each settled market’s mid-price 12 hours before it closed and compares it with how often markets at that price actually resolved YES. In a well-calibrated market, contracts priced around 0.30 should win about 30% of the time.
settled = client.get_markets(status="settled", series_ticker="KXHIGHNY",
min_settled="2026-10-01", max_settled="2026-11-01")
def mid_before_close(row, hours=12):
t = row.close_time - pd.Timedelta(hours=hours)
c = client.get_candlesticks(row.ticker, start=t - pd.Timedelta(hours=1), end=t,
series_ticker="KXHIGHNY")
return ((c.yes_bid_close + c.yes_ask_close) / 2).iloc[-1] if len(c) else float("nan")
settled["prob_12h"] = settled.apply(mid_before_close, axis=1) # one request per market
settled["won"] = (settled.result == "yes").astype(int)
settled["bucket"] = pd.cut(settled.prob_12h, bins=[0, .1, .3, .5, .7, .9, 1])
settled.groupby("bucket", observed=True).won.agg(["mean", "count"])
previous_price column for this. On settled markets it’s usually already close to 0 or 1, because by then the outcome was known.Save data for later#
trades = client.get_trades("KXHIGHNY-26NOV27-B57.5")
trades.to_parquet("trades.parquet") # keeps the dtypes, including UTC times
trades = pd.read_parquet("trades.parquet")
Limits and notes#
series_ticker to get_candlesticks to avoid extra lookups.get_orderbook).get_markets by default. Use mve_filter="exclude" to leave them out.Contact#
For any enquiries related to ads, software bugs, or anything else, please email bhatwadekarenterprises@gmail.com.