Metadata-Version: 2.4
Name: quarrybt
Version: 0.1.1
Summary: A native desktop futures backtesting terminal: custom-painted chart, event-driven engine, order-flow tooling and a Python strategy studio.
Project-URL: Homepage, https://github.com/ryferrari/quarrybt
Project-URL: Source, https://github.com/ryferrari/quarrybt
Project-URL: Issues, https://github.com/ryferrari/quarrybt/issues
Author: Ryley Ferrari
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Keywords: backtesting,futures,order-flow,quantitative,trading
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: X11 Applications :: Qt
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.11
Requires-Dist: numpy<3,>=1.24
Requires-Dist: pandas<4,>=2.0
Requires-Dist: pyflakes<4,>=3.0
Requires-Dist: pyside6<7,>=6.6
Description-Content-Type: text/markdown

# Quarry

A native desktop backtesting terminal built in Python. It reads multiple schemas,
from OHLCV CSVs to hundred-gigabyte MBO folders, reconstructing order flow and
per-candle volume footprints in a single pass. Strategies are written in Python
in the program and run on an event-driven engine, with results on a candlestick
chart with trade markers, an equity curve, a trade log, and performance metrics.

<img width="1920" height="1080" alt="Strategy Studio with a footprint chart and backtest results" src="https://github.com/user-attachments/assets/496e1076-e175-4e38-99b8-0d1a95449dcd" />

- **Data** Reads CSVs, folders, .zips
- **Order Flow** Displays buy/sell volume, trades, cvd, delta, order ids, block prints, and more
- **Volume Footprint** A per-candle ladder in three styles — bid × ask, profile and
  delta — with imbalance stacking, POC marking and bar totals
- **Replay Mode** replays candles forming tick by tick, trades, depth of market, time & sales.
  Allows for demo trading
- **Editor** built in IDE using Python to build strategies, also allows for python scripts to
  be imported
- **Metrics** Equity curve, Monte Carlo, Trade logs, Random entries, Walk-Forward testing
- **Parameter Sweeps** Reads variables from the strategy and runs tests to find the most
  optimal parameters

## Install

If you already have Python 3.11+, the quickest route is [pipx](https://pipx.pypa.io),
which puts Quarry in its own environment without touching your system packages:

```bash
pipx install quarrybt
quarry
```

Otherwise download the installer for your platform from
[Releases](https://github.com/ryferrari/quarrybt/releases) — a `.pkg` for macOS
and an `.exe` for Windows, neither of which needs Python installed.

## Run from source

```bash
python3.13 -m venv .venv
./.venv/bin/python -m pip install -r requirements.txt
./.venv/bin/python main.py
```

engine check:

```bash
./.venv/bin/python scripts/run_backtest.py quarry/sample_data/SAMPLE_15m.csv
```

## Writing a strategy

Subclass `Strategy`, implement `init()` (compute indicators once) and `next()`
(per-bar logic). Orders placed in `next()` fill at the **next bar's open** (no
look-ahead).

<img width="1920" height="1080" alt="A strategy in the editor beside its entry, stop and target on the chart" src="https://github.com/user-attachments/assets/fb5c3ba1-231a-4ab7-9bab-d180f4b0506f" />

```python
class MACrossover(Strategy):
    def init(self):
        self.fast = self.sma(self.close, 9)
        self.slow = self.sma(self.close, 21)
        self.plot("SMA 9", self.fast, color="#38bdf8")

    def next(self):
        if self.crossover(self.fast, self.slow) and not self.is_long:
            self.close_position(); self.buy()
        elif self.crossunder(self.fast, self.slow) and not self.is_short:
            self.close_position(); self.sell()
```

Helpers: `self.sma/ema/rsi`, `self.crossover/crossunder`, `self.buy/sell/close_position`,
`self.plot(...)`, state `self.is_long/is_short/is_flat/position`, arrays
`self.open/high/low/close/volume`, current bar `self.i`.

Strategies that need the ladder get `self.footprint()`, plus `self.buy_volume`,
`self.sell_volume`, `self.delta`, `self.cvd`, `self.max_trade` and
`self.trade_count`. These are `None` on a plain OHLCV CSV, so a flow strategy
fails loudly instead of trading a fabricated flat delta — guard with
`self.has_flow` or `self.has_footprint`.

## Replay

Replay walks the chart forward through history. Where the import carried data
finer than the chart's timeframe, candles form tick by tick out of the underlying
prints, and the footprint ladder fills in with it. Speed can be adjusted from
0.5x up to 60x.

The book and the tape come with it. Both panels are rebuilt from the MBO stream
at whatever instant the replay is sitting on, so the ladder shows the resting
size that was actually there and the tape shows the prints in order with their
aggressor side. Both detach into their own windows, and DOM rows line up with
the chart's price rows.

<img width="690" height="719" alt="Time and Sales and Depth of Market panels detached into their own windows" src="https://github.com/user-attachments/assets/29191505-74ed-4209-968d-9c4efb49c1ec" />

Demo trading is featured in replay mode and can be saved as a project. Features
market, limit, and stop orders. Also uses the same walk-forward engine.

## Tests

```bash
./.venv/bin/python tests/run_all.py            # the fast tier — 56 suites, ~40s
./.venv/bin/python tests/run_all.py --slow     # plus the real-data tier
./.venv/bin/python tests/run_all.py -k liq     # only names containing "liq"
```

Each suite is a standalone script that asserts, renders a PNG, or both, and
passes by exiting zero. The runner shells them out, so one Qt crash cannot take
the run down with it. It prints an assertion count beside each result: about
half of these render and assert nothing.

`tests/slow/` needs an external SSD and a warm cache, and is excluded by
default. See `tests/slow/README.md`.

## Build a distributable

- **macOS** (`.app` + `.pkg`): `./scripts/build_mac.sh [arm64|x86_64]` → `dist/<arch>/Quarry.app`, `dist/Quarry-<arch>.pkg`
- **Windows** (`.exe`): `scripts\build_win.bat` → `dist\Quarry\Quarry.exe`

Both use the bundled `quarry.spec` (PyInstaller). Icons come from
`assets/`; regenerate them with `PYTHONPATH=. .venv/bin/python scripts/make_icon.py`.

### macOS

There is no universal binary. PySide6 ships `universal2` wheels but numpy and
pandas do not, so a single environment can only ever produce one architecture.
Each is therefore built from its own venv and shipped as its own `.pkg`:

| Target | Runs on | venv |
| --- | --- | --- |
| `arm64` | Apple Silicon, M1 and later | `.venv` |
| `x86_64` | Intel Macs, and Apple Silicon via Rosetta | `.venv-x86` |

The Intel environment is built under Rosetta, with versions pinned to match
`.venv` so the two builds cannot drift apart:

```bash
arch -x86_64 /Library/Frameworks/Python.framework/Versions/3.13/bin/python3.13 \
  -m venv .venv-x86
arch -x86_64 .venv-x86/bin/python3 -m pip install --only-binary=:all: \
  "numpy==2.5.1" "pandas==3.0.5" "PySide6==6.11.1" "pyinstaller==6.21.0" "pyflakes>=3.0"
```

`--only-binary` matters: without it pip falls back to compiling numpy
and pandas from source, which takes an hour before failing.

The `arch` prefix is not optional and is the one genuinely subtle part. Python
is installed as a `universal2` binary, so `.venv-x86/bin/python` launches as
**arm64** on Apple Silicon unless forced otherwise and PyInstaller reads its
target architecture off the interpreter it happens to be running under. Choose
the right venv but forget the prefix and the build targets arm64, then dies on
the first x86_64 numpy extension it collects. `build_mac.sh` applies the prefix
itself and verifies the interpreter really is the requested architecture before
it starts.

The macOS floor is 13.0. macOS 26 Tahoe is the last release to support Intel
Macs, so the `x86_64` build has a finite shelf life.

### Checking a build

A packaged app is the one configuration the test suite cannot reach: the
source tree can be green while the bundle dies on launch, because freezing
changes the import system, the paths and the multiprocessing start method.
So the check ships inside the binary, and both build scripts run it and
refuse to report success if it fails:

```bash
dist/arm64/Quarry.app/Contents/MacOS/Quarry --self-test
```

It verifies the bundled sample data resolves, that `~/.quarry` is
writable, that the SVG icon plugin actually paints rather than silently
producing blanks, and that both worker pools round-trip including the
sweep's `forkserver` context, which has to re-exec the bundle. Run it from
`/`, as the build scripts do: Finder launches with that working directory,
and a relative path that only resolves from the project root is the classic
way for a build to pass on the machine that made it.

### Signing and notarizing

Unsigned builds run on the machine that made them and are blocked by
Gatekeeper everywhere else. Signing needs a paid Apple Developer account;
with one, set these and rerun the script, which otherwise skips both steps:

```bash
export DEV_ID_APP="Developer ID Application: Your Name (TEAMID)"
export DEV_ID_INSTALLER="Developer ID Installer: Your Name (TEAMID)"
export NOTARY_PROFILE=quarry    # xcrun notarytool store-credentials
```

`security find-identity -v -p codesigning` lists what a machine actually
has. The hardened runtime entitlements are in `packaging/entitlements.plist`
and are not optional for a frozen Python app. Windows signing is unrelated
and needs a certificate from a commercial CA.

## Project layout

```
main.py                  entry point
quarry/data/loader.py    CSV → normalized OHLCV DataFrame
quarry/engine/           events, broker, strategy base, backtest loop
quarry/stats/metrics.py  performance metrics
quarry/strategies/       example strategies
quarry/gui/              theme, chart, equity, panels, studio, main window
scripts/                 sample generator, headless runner, build scripts
tests/                   engine/ data/ gui/ fast tiers, slow/ real-data tier
```

## License

GPL-3.0-or-later. See [LICENSE](LICENSE).

Qt is used through PySide6 under the LGPLv3, and the packaged builds bundle Qt's
libraries. The license texts and the accompanying notice ship inside the builds at
`quarry/assets/licenses/`; `Quarry --licenses` prints the notice along with the
exact Qt version. Qt is dynamically linked and its frameworks and DLLs can be
replaced in place, which is what the LGPLv3 asks for.

Qt Virtual Keyboard is GPLv3-only rather than LGPLv3 and is unused, so it is
stripped from the packaged builds. The UI font is Overused Grotesk under the
SIL OFL 1.1.
