Technical research guide

How to Backtest Polymarket Historical Data Without Look-Ahead Bias

A credible Polymarket backtest must use only information available at each simulated decision, trade at a realistic executable price, apply fees and slippage, and settle positions from the written market outcome. The official Data API provides historical outcome prices and matched trades, but a sampled price series is not a replay of the historical order book.

If your strategy depends on queue position, spread capture or order-book depth, begin recording live book updates before testing it. Do not manufacture historical liquidity from candle-like price points.

Define the claim before downloading data

A testable strategy has five components:

  1. Universe: markets eligible at the decision time.
  2. Signal: data observable before the order.
  3. Entry: the first price and time at which a realistic fill could occur.
  4. Exit: a rule based on later observable data or final settlement.
  5. Sizing: a rule that cannot use future profit or future liquidity.

“Buy markets that eventually win when they are below 40¢” is not a strategy. It uses the final result to select the trade. A valid version might be: “At 12:00 UTC each day, buy YES at the next observed executable ask when an external forecast available at that time exceeds the market midpoint by ten percentage points.”

Write the rule in a frozen research note before inspecting returns.

Understand Polymarket’s data identifiers

Polymarket organizes data as events, markets and outcomes. An event can contain multiple markets. Each binary market has separate YES and NO outcome identifiers.

The official documentation says the identifier depends on protocol version:

  • a CTF market uses a token ID;
  • a Protocol V2 market uses a position ID.

The unified SDK calls either one an asset_id. Historical-price and order-book requests need the outcome identifier, not merely the event slug or condition ID.

Store this mapping with the test:

FieldPurpose
Event ID and slugGroups related questions
Market ID and condition IDIdentifies the binary contract
Protocol versionDetermines the outcome identifier field
YES asset IDFetches YES price history
NO asset IDFetches NO price history
Close/resolution statusPrevents trading after closure
Rule text and sourceDetermines valid settlement

Never infer that the first token is always YES without checking the outcome mapping.

Official data sources for a backtest

Market discovery

Use the Gamma API or official SDK to list events and markets. Querying by closed status and tags helps build a universe, but the current market record can contain information updated after your simulated date. Archive snapshots if universe reconstruction matters.

Price history

The Data API endpoint is:

GET https://data-api.polymarket.com/v2/prices-history

It accepts an outcome token or position ID and one time form: a relative interval, a start/end range or an as_of point. The documentation says explicit ranges span at most 15 days. Points are returned oldest first and include resolution_seconds.

Retention varies by resolution. Current documentation states that one-minute data lasts at least seven days, five-minute data at least 60 days and thirty-minute data at least 90 days. Three-hour and twelve-hour data is permanent; full history defaults to twelve-hour buckets.

Matched trades

The analytics endpoint /v2/trades returns price, size, side, outcome, wallet, timestamp and transaction hash for recent or filtered trades. The documentation says results are newest first and that share size and price are expressed in shares and USDC per share.

Trade prints show transactions that occurred. They do not prove that your additional order could have filled at the same price and size.

Live order books

The CLOB endpoint and market WebSocket provide current book snapshots and changes. The official documentation does not provide a general historical order-book replay endpoint. This is a material limitation for market-making and high-frequency tests.

Minimal Python data pull

The following read-only example downloads one day of hourly observations for a known outcome ID:

import requests
import pandas as pd

TOKEN_ID = "replace_with_yes_outcome_id"

params = {
    "token_id": TOKEN_ID,
    "interval": "1d",
    "bucket_seconds": 3600,
}

r = requests.get(
    "https://data-api.polymarket.com/v2/prices-history",
    params=params,
    timeout=20,
)
r.raise_for_status()
payload = r.json()

df = pd.DataFrame(payload["data"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="s", utc=True)
df["price"] = pd.to_numeric(df["price"])
df = df.sort_values("timestamp").drop_duplicates("timestamp")
print(df[["timestamp", "price", "resolution_seconds"]])

Check the actual timestamp unit in the endpoint response you receive; SDK examples may normalize it differently from raw API examples. Preserve the unmodified JSON before transforming it.

For pagination, follow next_cursor while has_more is true. Respect documented limits and retry transient errors with capped exponential backoff.

Model a fill, not a chart point

The simplest backtest error is buying at the same price that generated the signal. If the 12:00 bucket closes at 40¢ and triggers an entry, fill no earlier than the next observation. Otherwise the strategy uses a price before it was known.

A conservative hierarchy is:

  1. Historical book available: walk the ask levels for a buy or bid levels for a sell.
  2. Trade prints available: require later trades with sufficient cumulative size and add adverse price movement.
  3. Only sampled prices available: use the next point plus an explicit spread/slippage penalty and label the result approximate.

Never fill a $100,000 simulated order from a single $50 trade at the target price.

Add category fees correctly

Polymarket International’s fee schedule varies by category and share price. Makers are not charged, while taker fees apply to selected categories. Programs can also create rebates.

Your backtest should record the schedule effective on the simulated date, not today’s schedule retroactively. Apply the published formula to every fill and keep gross P&L separate from fees.

If the historical fee schedule cannot be verified, run a sensitivity table:

ScenarioEntry frictionExit frictionFee assumption
Optimistichalf spreadhalf spreadlowest documented case
Basefull spreadfull spreadapplicable taker formula
Stressfull spread + impactfull spread + impactfee plus no rebate

A strategy that works only in the optimistic row is not robust.

Handle settlement and invalid markets

At settlement, a winning share normally pays $1 and a losing share pays $0. But the test must use the market’s actual resolved outcome and rules, including Invalid or cancellation treatment where relevant.

Do not infer settlement from a news headline. Store:

  • final outcome;
  • resolution timestamp;
  • rule text;
  • source used;
  • dispute or clarification status;
  • redemption value.

Positions held past your dataset’s end are open, not profitable by assumption. Mark them to a documented price or exclude them under a pre-declared rule.

Prevent the six most damaging biases

Look-ahead bias

No data timestamped after the decision can influence the signal, universe or size.

Survivorship bias

Do not test only markets that remain easy to find. Include closed, illiquid, invalid and deleted-from-navigation observations when the universe rule would have selected them.

Selection bias

Choosing attractive categories after seeing their results overstates performance. Reserve an untouched out-of-sample period.

Liquidity bias

Apply size constraints based on liquidity known at entry. Today’s large market does not prove yesterday’s book was deep.

Rule-change bias

Fee schedules, APIs and product mechanics change. Version assumptions by date.

Multiple-testing bias

Trying hundreds of thresholds and reporting the best one creates a false discovery. Disclose the number of variants and use walk-forward validation.

Metrics that reveal more than final profit

Report:

  • number of markets and trades;
  • gross and net P&L;
  • return on capital;
  • maximum drawdown;
  • win rate and average win/loss;
  • turnover and average holding time;
  • fee and slippage share of gross edge;
  • exposure by category and deadline;
  • performance by probability bucket;
  • calibration of predicted versus realized outcomes.

Prediction strategies should also be scored with Brier score or log loss when they produce probabilities. A profitable trading threshold can coexist with poor probability calibration, and vice versa.

A publication-ready backtest protocol

  1. Publish the hypothesis and date range.
  2. Pin API schema, code and dependency versions.
  3. Save raw responses with retrieval timestamps.
  4. Document every exclusion and missing record.
  5. Separate discovery, validation and final test periods.
  6. Apply next-tick execution, fees and capacity limits.
  7. Stress spreads and unavailable exits.
  8. Report all tested variants or correct for search.
  9. Provide enough code and identifiers to reproduce the result.
  10. State what the dataset cannot prove.

Frequently asked questions

Does Polymarket provide historical price data?

Yes. The official Data API provides outcome price history at documented resolutions and retention windows.

Can I download historical order books?

The official documentation provides current REST books and live WebSocket updates, but does not document a general historical order-book replay endpoint. Record live updates yourself if book reconstruction is essential.

Is a midpoint a realistic fill price?

Not necessarily. A market order crosses to the best available opposite quote and can consume multiple levels. A midpoint can be useful for valuation but should not automatically be used as execution.

How do I prevent look-ahead bias?

Generate the signal only after its source data closes and fill at a later observable price. Build the market universe from information available at the simulated time.

Should settled winners be valued at $1?

Use the actual resolution and redemption value. Do not apply $1 merely because later news suggests your selected outcome was correct.

Official sources

Research notice: A backtest is a model, not evidence of future profit. Historical data can omit liquidity, latency and operational failures. Never deploy capital based only on an in-sample result.

Update log

  • November 17, 2026: Verified Data API v2 price-history windows, trade fields, current order-book endpoints and live stream behavior.
Polymarket Central Quant Research Desk

Reviewed by Market Data and Methodology Review. Updated November 17, 2026. Risk level: High.