# Polymarket Backtesting in Python with Order Book Data

Load a real BTC 5-minute market sample, inspect its CSV quotes and depth, and simulate buying UP and selling after 60 seconds. The script uses only the Python standard library, with no pandas or other package installation required.

[Download sample data](/samples/polymarket-btc-5m-20261008-1500.zip) · [Download the Python script](/tutorial/backtest_sample.py) · [View the measured output](/tutorial/example-result.json)

## Run the example

Extract the sample into a directory named `sample`, with the tutorial script alongside it. Use an existing Python virtual environment or create one as below. No third-party dependencies are installed for this tutorial.

```sh
python3 -m venv .venv
source .venv/bin/activate
python backtest_sample.py --data-dir sample --output result.json
```

On Windows, activate the environment with `.venv\Scripts\activate`. The data directory must contain ticks.csv, depth.csv, outcomes.csv and manifest.json.

The script checks row counts and market identifiers, and rejects duplicate join keys, invalid book prices and depth rows without a matching quote. The output records SHA-256 hashes of the input CSV files.

## Decisions and timestamps

The example decides to buy after receiving the first eligible quote inside the scheduled market window. It does not use winner_side or target to choose an outcome. Default order latency is 250 milliseconds.

At each simulated arrival, select the last stored snapshot whose receive time is no later than arrival. A message with an earlier source time but a later receive time is unavailable until received. Reject snapshots older than two seconds instead of filling gaps.

This stored snapshot is an approximation of the market at order arrival. Without actual round-trip timing and exchange execution records, the example cannot prove that a historical order would have filled.

## Walk the book and preserve partial fills

Buys consume UP asks from lowest to highest price; sells consume UP bids from highest to lowest. By default, only 50% of each level's displayed quantity is available to the simulation. Any remainder stays unfilled.

After entry, wait 60 seconds and apply order latency again to the exit. Request no more than the simulated purchased quantity. If the exit is partial, report residual inventory and cash flow; do not label the cash flow as closed-position profit.

```sh
python backtest_sample.py --data-dir sample --quantity 100 --latency-ms 250 --hold-seconds 60 --size-fraction 0.5 --max-staleness-ms 2000 --fee-bps 0 --output result.json
```

fee-bps applies an illustrative fee to simulated traded notional. The zero default is not a claim about venue fees. Replace it with the rules applicable to the market and date for actual research. Walking levels accounts for visible-depth price differences, but additional market impact and passive queue execution are not modeled.

## Output from this sample

Default parameters simulate buying 100 UP shares at a volume-weighted price of $0.39 and selling 100 at $0.217. The exit walks two levels: 70 shares at $0.22 and 30 at $0.21. Under the illustrative zero-fee assumption, closed-position P&L is −$17.30.

This is one teaching round trip under fixed parameters. It has no train/test split, statistical significance or tradable-return claim. When changing parameters, use the JSON from your own run.

Of the sample's 552 ticks, 207 are pre-open. The last in-window observation was received at `15:04:25.770 UTC`, before the window ended. The largest interval between stored in-window observations is 91.498 seconds. Do not treat the file as a continuous full-book record.

## Before using the historical archive

Group by event_slug and inspect timestamps, disconnects and duplicates for each archive version. Combine adjacent UTC dates for cross-midnight windows and load every archive part. Disclose approximations when receive time is missing.

Use outcomes only for retrospective evaluation. Exclude winner_side, target and future arrivals from predictive features. A multi-market strategy also needs out-of-sample evaluation, fee and latency scenarios, and counts and reasons for excluded markets.

Predict.fun raw observations are YES books, with DOWN quotes derived by complement. This example only supports the supplied Polymarket CSV sample; it is not a Predict.fun execution model. Join underlying BTC prices separately by provider and channel.

[Dataset specifications](/en/datasets/polymarket-btc-5m/) · [Schema and timestamps](/en/schema/) · [Underlying-price study](/en/research/bolt-price-semantics/) · [Historical file directory](/en/downloads/)
