QTrade is a small, modular Python library for backtesting trading strategies and training reinforcement learning agents on financial data.
- 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
TradingEnvwith pluggable Action / Observation / Reward schemes, ready to drop intostable-baselines3and 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.
pip install qtrade-libOptional extras:
pip install "qtrade-lib[rl]" # adds stable-baselines3 for RL evaluation utilsTo work from source:
git clone https://github.com/gguan/qtrade.git
cd qtrade
pip install -e ".[dev]"
pre-commit install
pytestimport 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.
- User Guide
- Multi-asset / portfolio backtests
- RL trading environment
- API reference
- Releasing
- Changelog
- Python ≥ 3.10
- Runtime dependencies declared in
pyproject.toml(numpy, pandas, scipy, matplotlib, bokeh, gymnasium, mplfinance, tqdm).
This project is inspired by:
- backtesting.py — single-asset backtest API design
- tensortrade — RL trading framework
MIT — see LICENSE.