Skip to main content

A Python library for backtesting trading strategies and applying reinforcement learning to trading.

Project description

PyPI version Python versions CI Docs License Code style: ruff

QTrade

QTrade is a small, modular Python library for backtesting trading strategies and training reinforcement learning agents on financial data.

Features

  • Single-asset and portfolio backtesting: pass one DataFrame for single-asset, or a dict[str, DataFrame] for multi-asset / portfolio strategies sharing one cash pool.
  • Walk-forward optimization: rolling-window training + immediate out-of-sample test, the standard antidote to in-sample overfitting.
  • RL trading environment: a Gymnasium TradingEnv with pluggable Action / Observation / Reward schemes, ready to drop into stable-baselines3 and friends.
  • Bokeh reports: equity, drawdown, per-asset OHLC panels, trade scatter — saved as a single self-contained HTML.
  • Curated metrics: Sharpe, Sortino, Calmar, Omega, max drawdown duration, win rate, profit factor, etc.

See COMPARISON.md for an honest take on where QTrade fits next to backtrader / vectorbt / Backtesting.py.

Installation

pip install qtrade-lib

Optional extras:

pip install "qtrade-lib[rl]"   # adds stable-baselines3 for RL evaluation utils

To work from source:

git clone https://github.com/gguan/qtrade.git
cd qtrade
pip install -e ".[dev]"
pre-commit install
pytest

Quickstart

import yfinance as yf
from qtrade.backtest import Strategy, Backtest

class SmaCrossover(Strategy):
    n1 = 5
    n2 = 20

    def prepare(self):
        for df in self._data.values():
            df['sma1'] = df['Close'].rolling(self.n1).mean()
            df['sma2'] = df['Close'].rolling(self.n2).mean()

    def on_bar_close(self):
        s1, s2 = self.data['sma1'], self.data['sma2']
        if s1.iloc[-2] < s2.iloc[-2] and s1.iloc[-1] > s2.iloc[-1]:
            self.buy()
        elif s1.iloc[-2] > s2.iloc[-2] and s1.iloc[-1] < s2.iloc[-1]:
            self.close()

data = yf.download("GC=F", start="2023-01-01", end="2024-01-01",
                   interval="1d", multi_level_index=False)

bt = Backtest(data, SmaCrossover, cash=10_000, trade_on_close=True)
bt.run()
bt.show_stats()
bt.plot()

For a multi-asset / walk-forward example, see examples/portfolio_strategy.py.

Documentation

Requirements

  • Python ≥ 3.10
  • Runtime dependencies declared in pyproject.toml (numpy, pandas, scipy, matplotlib, bokeh, gymnasium, mplfinance, tqdm).

References

This project is inspired by:

License

MIT — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qtrade_lib-0.5.0.tar.gz (7.3 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

qtrade_lib-0.5.0-py3-none-any.whl (45.0 kB view details)

Uploaded Python 3

File details

Details for the file qtrade_lib-0.5.0.tar.gz.

File metadata

  • Download URL: qtrade_lib-0.5.0.tar.gz
  • Upload date:
  • Size: 7.3 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for qtrade_lib-0.5.0.tar.gz
Algorithm Hash digest
SHA256 75d32e8c7df0721a6edd062777fb4de2ae4e7c122849c493fcb02d38c7f16d44
MD5 e87cc7a5129f211c09eecaeb5f2323bd
BLAKE2b-256 df9162ffa57201df7e8df57ffbfc7dea2a67d93e48d5af18bfffa2cf34894443

See more details on using hashes here.

Provenance

The following attestation bundles were made for qtrade_lib-0.5.0.tar.gz:

Publisher: release.yml on gguan/qtrade

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file qtrade_lib-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: qtrade_lib-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 45.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for qtrade_lib-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 368ae187ee824c5cf821801e7d45cfb315d17a38277b99cc206f494cfa6e3229
MD5 7fdcda5c98cdc974bbd28eece7e6f6c3
BLAKE2b-256 b963886c61aea474ac5d39ffd03c4ecefe3e505e2639ec89373e0438394c3ae7

See more details on using hashes here.

Provenance

The following attestation bundles were made for qtrade_lib-0.5.0-py3-none-any.whl:

Publisher: release.yml on gguan/qtrade

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page