Metadata-Version: 2.4
Name: prosperity5bt
Version: 0.0.0
Summary: Backtester for IMC Prosperity 5 algorithms
Author-email: Jasper van Merle <jaspervmerle@gmail.com>, Karl Oddshammar <karloddsh@proton.me>
License: MIT License
        
        Copyright (c) 2024 Karl Oddshammar
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Repository, https://github.com/alexoddsh/imc-prosperity-5-backtester
Project-URL: Issues, https://github.com/alexoddsh/imc-prosperity-5-backtester/issues
Project-URL: Changelog, https://github.com/alexoddsh/imc-prosperity-5-backtester/releases
Keywords: imc,prosperity,backtest,backtester
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: ipython>=8.18.1
Requires-Dist: jsonpickle>=4.0.2
Requires-Dist: orjson>=3.10.15
Requires-Dist: tqdm>=4.67.1
Dynamic: license-file

# IMC Prosperity 5 Backtester

[![PyPI Version](https://img.shields.io/pypi/v/prosperity5bt)](https://pypi.org/project/prosperity5bt/)

This repository contains a backtester for [IMC Prosperity 5](https://prosperity.imc.com/) algorithms, based on [Jmerle's Prosperity 3 backtester](https://github.com/jmerle/imc-prosperity-3-backtester). The output it generates closely matches the format of the output generated by the official submission environment and is therefore compatible with the [Prosperity 3 Visualizer](https://github.com/jmerle/imc-prosperity-3-visualizer) (assuming your code contains the visualizer's required prerequisites as explained on the visualizer's homepage).

## Usage

```sh
# Install the latest version of the backtester
$ pip install -U prosperity5bt

# Backtest every day of Prosperity 4 round 1
$ prosperity5bt <path to algorithm file> 4 1
```

A backtest always runs one round of one data set. Both are given explicitly, and the only choice is whether to run
every day in that round or a single one:

```sh
# Every day of Prosperity 4 round 1
$ prosperity5bt algo.py 4 1

# Only day 0 of Prosperity 4 round 1
$ prosperity5bt algo.py 4 1 --day 0

# Prosperity 3 round 5, day 2
$ prosperity5bt algo.py 3 5 --day 2

# Negative day numbers work as-is
$ prosperity5bt algo.py 4 1 --day -2
```

See [Data Files](#data-files) for the data sets, rounds and days that are available.

### Other options

```sh
# Merge profit and loss across days
$ prosperity5bt algo.py 4 1 --merge-pnl

# Write algorithm output to custom file
$ prosperity5bt algo.py 4 1 --out example.log

# Skip saving the output log to a file
$ prosperity5bt algo.py 4 1 --no-out

# Backtest on custom data
# Requires the value passed to `--data` to be a path to a directory laid out like
# prosperity5bt/resources, i.e. containing resources-<n>/round<n>/ subdirectories.
# Point it at the resources root, not at an individual resources-<n> directory.
$ prosperity5bt algo.py 4 1 --data prosperity5bt/resources

# Print trader's output to stdout while running
# This may be helpful when debugging a broken trader
$ prosperity5bt algo.py 4 1 --print
```

Run `prosperity5bt --help` for the full list.

## Python API

The backtester is usable as a library, not just a CLI. Install it into your project and call `backtest()`:

```python
from prosperity5bt import backtest

from my_algo import Trader

output = backtest(Trader, data_set=4, round_num=1)      # every day of the round
output = backtest(Trader, data_set=4, round_num=1, day=0)   # just day 0

print(output.data_set)            # 4
print(output.round_num)           # 1
print(output.days)                # [-2, -1, 0]
print(output.profit)              # total profit and loss across those days
print(output.profit_by_day)       # {-2: 77907.0, -1: 79023.0, 0: 78919.0}
print(output.profit_by_product)   # {"ASH_COATED_OSMIUM": -1616.0, ...}
```

The three selection arguments are positional too, so `backtest(Trader, 3, 5, 2)` is Prosperity 3 round 5 day 2.

Nothing is written to disk unless you ask for it — pass `out=` or call `output.save(...)`:

```python
output = backtest(Trader, 4, 1, merge_pnl=True, out="backtests/run.log")

log_text = output.log             # the merged output log, as a string
merged = output.merged            # the merged BacktestResult
for result in output.results:     # one BacktestResult per day
    print(result.day_num, result.profit, result.product_profits)
```

### `backtest(algorithm, data_set, round_num, day=None, **options)`

`algorithm` can be any of:

| Value | Behavior |
| --- | --- |
| A `Trader` class | A fresh trader per day, like the official submission environment |
| A `Trader` instance | One trader reused across every day, so state carries over |
| A module exposing `Trader` | A fresh trader per day; the module is never reloaded |
| A path (`str` or `Path`) to a file exposing `Trader` | A fresh trader per day; the module is reloaded between days, matching the CLI |

Keyword options:

| Option | Default | Meaning |
| --- | --- | --- |
| `data` | bundled data | Path to a custom resources directory |
| `file_reader` | – | A `FileReader` to take data from, instead of `data` |
| `match_trades` | `"all"` | `"all"`, `"worse"` or `"none"`; accepts the string or the `TradeMatchingMode` enum |
| `print_output` | `False` | Let the trader's stdout through instead of capturing it |
| `show_progress_bars` | `False` | Render a progress bar per day |
| `out` | `None` | Write the merged output log here; nothing is written when `None` |
| `merge_pnl` | `False` | Carry profit and loss across day boundaries when merging |
| `original_timestamps` | `False` | Keep each day's own timestamps when merging |
| `on_day_start` | `None` | Called with the day number before each day runs |
| `on_day_complete` | `None` | Called with each day's `BacktestResult` as it finishes |

Anything that can't be resolved raises `BacktestError` rather than exiting the process — an unknown data set, a
round with no data, or a day the round doesn't have:

```python
from prosperity5bt import BacktestError, backtest

try:
    output = backtest(Trader, 9, 1)
except BacktestError as e:
    print(e)  # data set 9 not found, available data sets: 3, 4
```

### Lower-level pieces

`backtest()` is a thin composition of exported building blocks, useful if you want to drive things yourself:

```python
from prosperity5bt import create_file_reader, resolve_days, run_backtest

file_reader = create_file_reader()                   # or FileSystemReader(path) / your own FileReader
print(file_reader.data_sets())                       # [3, 4]

days = resolve_days(file_reader, 4, 1)               # [-2, -1, 0]

result = run_backtest(Trader(), file_reader, 4, 1, days[0], False, "all", True, False)
```

`format_output`, `write_output`, `merge_results` and `validate_data_set` are exported too, as are `read_day_data`,
`has_day_data` and `LIMITS` for working with the data directly.

## Order Matching

Orders placed by `Trader.run` at a given timestamp are matched against the order depths and market trades of that timestamp's state. Order depths take priority, if an order can be filled completely using volume in the relevant order depth, market trades are not considered. If not, the backtester matches your order against the timestamp's market trades. In this case the backtester assumes that for each trade, the buyer and the seller of the trade are willing to trade with you instead at the trade's price and volume. Market trades are matched at the price of your orders, e.g. if you place a sell order for €9 and there is a market trade for €10, the sell order is matched at €9 (even though there is a buyer willing to pay €10, this appears to be consistent with what the official Prosperity environment does).

Matching orders against market trades can be configured through the `--match-trades` option:
- `--match-trades all` (default): match market trades with prices equal to or worse than your quotes.
- `--match-trades worse`: match market trades with prices worse than your quotes, inspired by [team Linear Utility's Prosperity 2 write-up](https://github.com/ericcccsliu/imc-prosperity-2).
- `--match-trades none`: do not match market trades against orders.

Limits are enforced before orders are matched to order depths. If for a product your position would exceed the limit, assuming all your orders would get filled, all your orders for that product get canceled.

## Data Files

Bundled data lives in `prosperity5bt/resources/`, one `resources-<n>` directory per Prosperity edition, each containing one `round<n>` directory per round:

```
prosperity5bt/resources/
├── resources-3/          # Prosperity 3
│   └── round0 … round8/
└── resources-4/          # Prosperity 4
    └── round0 … round5/
```

| Data set | Rounds | Days | Currency | Conversion observations |
| --- | --- | --- | --- | --- |
| 3 | 0–8 | r0: -1 · r1: -2…0 · r2: -1…1 · r3: 0…2 · r4: 1…3 · r5: 2…4 · r6: 0…6 · r7: 0…5 · r8: -1…1 | SEASHELLS | rounds 4 and 5 (`MAGNIFICENT_MACARONS`) |
| 4 | 0–5 | r0: -2,-1 · r1: -2…0 · r2: -1…1 · r3: 0…2 · r4: 1…3 · r5: 2…4 | XIRECS | none |

Each round directory holds `prices_round_<n>_day_<d>.csv` and, where available, `trades_round_<n>_day_<d>.csv` and `observations_round_<n>_day_<d>.csv`. Prices data is required; trades and observations are optional.

Adding a new data set is a matter of dropping a `resources-<n>` directory into `prosperity5bt/resources/` — it is discovered automatically, and becomes the default when it is the highest-numbered one. Products also need position limits added to `LIMITS` in `prosperity5bt/data.py`; a currency in `DEFAULT_CURRENCIES` and a conversion product in `OBSERVATION_PRODUCTS` are only needed if the data itself doesn't imply them.

To convert a submission log into data files, use `parse_submission_logs.py`:
```sh
$ python -m prosperity5bt.parse_submission_logs <path to log file> <round> <day> --data-set 5
```

## Environment Variables

During backtests three environment variables are set for the trader to know what it's being backtested on: `PROSPERITY5BT_DATA_SET` contains the data set number, `PROSPERITY5BT_ROUND` the round number and `PROSPERITY5BT_DAY` the day number. Note that these environment variables do not exist in the official submission environment, so make sure the code you submit doesn't require them to be defined.

## Development

Follow these steps if you want to make changes to the backtester:
1. Install [uv](https://docs.astral.sh/uv/).
2. Clone (or fork and clone) this repository.
3. Open a terminal in your clone of the repository.
4. Create a venv with `uv venv` and activate it.
5. Run `uv sync`.
6. Any changes you make are now automatically taken into account the next time you run `prosperity5bt` inside the venv.
