QuantJourney Backtester: A Python-Native Engine for Building and Testing Trading Strategies
Most trading strategies look good on paper. You come up with an idea, write a few lines of Python, test it against historical market data, and get an equity curve showing how much money the strategy would have made.
But there’s a problem.
A profitable backtest doesn’t necessarily mean you have a profitable trading strategy.
What about transaction costs? Slippage? Rebalancing? Look-ahead bias? Market crashes? Did your strategy actually work on data it had never seen before?
These details can completely change the results.
That’s where QuantJourney Backtester comes in.
It’s an open-source, Python-native backtesting engine that helps researchers turn trading ideas into reproducible research.
Instead of giving you just an equity curve, it produces a complete research packet containing performance metrics, execution details, drawdowns, risk analysis, optimization results, and reports.
Let’s explore how it works and how you can get started.
What Is QuantJourney Backtester?
QuantJourney Backtester takes a trading strategy and simulates how it would have performed using historical market data.
Its workflow looks like this:
Market Data → Features → Signals → Target Weights / Orders → Fills → Positions → NAV → Metrics → Reports
Every stage is explicit.
For example, a moving average strategy generates signals. Those signals become portfolio weights. The engine simulates trades, updates cash and positions, and calculates the portfolio’s net asset value (NAV).
The result is a reproducible backtest that you can inspect and verify.
1. Install QuantJourney Backtester
The package is available on PyPI and supports Python 3.11 or newer.
Start by creating a virtual environment:
python -m venv .venv
python -m venv .venv
Activate it.
On macOS or Linux:
source .venv/bin/activate
source .venv/bin/activate
On Windows:
.venvScriptsactivate
.venvScriptsactivate
Now install the package:
pip install quantjourney-bt
pip install quantjourney-bt
You can also install it using uv:
uv pip install quantjourney-bt
uv pip install quantjourney-bt
The current release in the supplied project documentation is 0.12.5.
If you want to explore walk-forward optimization, install the optional dependencies:
pip install "quantjourney-bt[wf]"
pip install "quantjourney-bt[wf]"
For data-related extras:
pip install "quantjourney-bt[data,wf]"
pip install "quantjourney-bt[data,wf]"
The [wf] extra adds Optuna for optimization examples, while [data] provides a yfinance benchmark fallback.
One important detail: Use a virtual environment instead of installing dependencies into your system Python. This avoids common dependency conflicts, especially on macOS.
2. Run Your First Backtest Without an API Key
One thing I like about this project is that you don’t need an API key just to test the installation.
Clone the repository:
git clone https://github.com/QuantJourneyOrg/quantjourney-bt.git
cd quantjourney-bt
git clone https://github.com/QuantJourneyOrg/quantjourney-bt.git
cd quantjourney-bt
Run the bundled sample strategy:
./strategy.sh example_weights_01_sma_daily
--sample-data
--output /tmp/qj-sample
./strategy.sh example_weights_01_sma_daily
--sample-data
--output /tmp/qj-sample
This uses deterministic sample data included with the project.
No account, API key, or external market-data connection is required.
Once the execution finishes, open:
/tmp/qj-sample/ExampleWeights01_DailySMATrend/dashboard.html
/tmp/qj-sample/ExampleWeights01_DailySMATrend/dashboard.html
You’ll also find files such as:
summary.json— summary of the backtest.metrics.csv— performance metrics.equity_curve.csv— portfolio equity over time.
Keep in mind that this is an installation and reporting demonstration. It doesn’t tell you how a strategy would have performed in historical markets.
3. Two Ways to Build Trading Strategies
QuantJourney supports two research modes: Weight Mode and Order Mode.
Understanding the difference is important because they solve different problems.
Weight Mode
Weight Mode focuses on portfolio allocation.
Instead of telling the engine to buy 10 shares of a stock, you tell it what percentage of your portfolio to invest in each asset.
For example:
target_weights = {
"AAPL": 0.40,
"MSFT": 0.35,
"CASH": 0.25
}
target_weights = {
"AAPL": 0.40,
"MSFT": 0.35,
"CASH": 0.25
}
This means:
- 40% allocated to Apple.
- 35% allocated to Microsoft.
- 25% held in cash.
This approach is useful for:
- Factor investing.
- Momentum strategies.
- Sector rotation.
- Long/cash strategies.
- Long/short portfolios.
- Volatility targeting.
- Risk parity.
You can also configure portfolio constraints and scheduled rebalancing.
Order Mode
Order Mode focuses on how trades actually execute.
It supports several order types:
| Order Type | What It Does |
| --------------------------- | ------------------------------------------------- |
| Market | Executes at the available market price |
| Limit | Executes at a specified price or better |
| Stop | Becomes active after reaching a trigger price |
| Stop-limit | Combines stop and limit conditions |
| Trailing stop | Follows the market using a trailing threshold |
| Bracket | Combines entry, stop-loss, and take-profit orders |
| OCO (One-Cancels-the-Other) | One order cancels the other |
| Order Type | What It Does |
| --------------------------- | ------------------------------------------------- |
| Market | Executes at the available market price |
| Limit | Executes at a specified price or better |
| Stop | Becomes active after reaching a trigger price |
| Stop-limit | Combines stop and limit conditions |
| Trailing stop | Follows the market using a trailing threshold |
| Bracket | Combines entry, stop-loss, and take-profit orders |
| OCO (One-Cancels-the-Other) | One order cancels the other |
For example, suppose your strategy wants to buy 100 shares of Apple.
Instead of assuming the trade happened at the closing price, the engine can simulate execution using commissions, slippage, volume participation, and fill rules.
This gives you a more realistic picture of how the strategy might behave.
4. Why Execution Costs Matter
Here’s something many beginners overlook.
A strategy can generate excellent returns before transaction costs but perform poorly after accounting for execution expenses.
Suppose a strategy generates $10,000 in gross profit.
Now consider:
ExpenseAmountGross profit$10,000Commissions$500Slippage$1,000Net profit$8,500
Your actual simulated profit is now $8,500.
That’s a 15% reduction.
QuantJourney lets you model commissions and slippage instead of assuming every trade executes perfectly.
It also handles an important detail: when simulating fills at the market open, range-sensitive slippage uses the previous completed bar. It forecasts volume capacity using lagged observations.
Why does this matter?
Because using the day’s final high, low, close, or full-day volume to simulate an earlier trade would introduce information that wasn’t available at execution time.
That’s a form of look-ahead bias.
The engine is designed to avoid that problem.
5. Build Strategies Using a Clear Workflow
QuantJourney separates strategy development into different responsibilities.
Here’s the structure:
| What You Want to Do | What to Use |
| ------------------------------- | -------------------- |
| Generate buy/sell signals | _compute_signals() |
| Calculate portfolio allocations | _compute_weights() |
| Submit individual orders | _compute_orders() |
| Apply risk constraints | risk_model=... |
| Configure rebalancing | RebalancePolicy(...) |
| Optimize parameters | Walk-forward/Optuna |
| What You Want to Do | What to Use |
| ------------------------------- | -------------------- |
| Generate buy/sell signals | _compute_signals() |
| Calculate portfolio allocations | _compute_weights() |
| Submit individual orders | _compute_orders() |
| Apply risk constraints | risk_model=... |
| Configure rebalancing | RebalancePolicy(...) |
| Optimize parameters | Walk-forward/Optuna |
This separation makes strategies easier to understand and maintain.
For example, suppose building a simple moving average strategy.
The idea is straightforward:
- Buy when the short moving average crosses above the long moving average.
- Exit when the short moving average falls below the long moving average.
Signal-generation example:
long_ma:
return 1
return 0″ data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
def generate_signal(short_ma, long_ma):
if short_ma > long_ma:
return 1
return 0
def generate_signal(short_ma, long_ma):
if short_ma > long_ma:
return 1
return 0
The function returns:
1when the strategy wants exposure.0when the strategy wants to stay in cash.
In a QuantJourney strategy, this logic belongs in the appropriate signal-generation method, such as _compute_signals().
The engine then handles the rest of the research workflow.
6. Test Whether Your Strategy Works Beyond Historical Data
Here’s where things get interesting.
A strategy might perform exceptionally well on historical data because its parameters were optimized specifically for that period.
But will it work on unseen data?
That’s the question walk-forward validation tries to answer.
Instead of optimizing and testing everything on the same dataset, walk-forward analysis divides the data into different periods.
The process works like this:
- Use an initial historical period to optimize strategy parameters.
- Test the selected parameters on a separate, unseen period.
- Move the testing window forward.
- Repeat the process.
QuantJourney supports walk-forward optimization with Optuna in its optional WF examples.
This helps you understand whether your strategy is learning a repeatable market pattern or fitting historical noise.
7. Get More Than an Equity Curve
A typical backtesting script might produce a single chart.
QuantJourney aims to produce a complete research packet.
Depending on the run and available features, you can get:
- Cumulative returns.
- Equity curves.
- Monthly returns heatmaps.
- Drawdown charts.
- Rolling risk statistics.
- Performance metrics.
- Optimization summaries.
- Walk-forward results.
- CSV and JSON artifacts.
- Static HTML dashboards.
- Run metadata.
The hosted QuantJourney platform adds further reporting capabilities, including crisis diagnostics, interactive dashboards, execution traces, and PDF tear sheets.
It’s worth understanding the distinction: these extended reports are hosted-platform features, not all part of the open-source local package.
8. Use AI Coding Assistants to Build Strategies
Another interesting feature is the project’s skills/ directory.
It contains guidance for AI coding assistants.
Instead of asking an AI assistant to invent an entire trading strategy from scratch, you can provide it with the project’s relevant skill instructions.
Here are five available skills:
| Skill | Purpose |
| ---------------------- | ----------------------------------------------- |
| `qj-strategy-ideas` | Turn trading ideas into runnable strategies |
| `qj-strategy-author` | Write strategy examples |
| `qj-strategy-reviewer` | Review strategy logic and execution assumptions |
| `qj-report-analyst` | Analyze reports and performance charts |
| `qj-config-helper` | Configure parameters and risk controls |
| Skill | Purpose |
| ---------------------- | ----------------------------------------------- |
| `qj-strategy-ideas` | Turn trading ideas into runnable strategies |
| `qj-strategy-author` | Write strategy examples |
| `qj-strategy-reviewer` | Review strategy logic and execution assumptions |
| `qj-report-analyst` | Analyze reports and performance charts |
| `qj-config-helper` | Configure parameters and risk controls |
For example, if you’re using Claude Code, you can point it to:
skills/qj-strategy-ideas/SKILL.md
skills/qj-strategy-ideas/SKILL.md
When reviewing an existing strategy, use:
skills/qj-strategy-reviewer/SKILL.md
skills/qj-strategy-reviewer/SKILL.md
This gives the coding assistant project-specific instructions about how the engine works.
It reduces the chances of generating code that ignores the project’s conventions.
9. Run the Example Strategies
The repository includes 51 example strategies.
To list them:
./strategy.sh --list
./strategy.sh --list
To check whether a strategy imports correctly without making a market-data request:
./strategy.sh example_weights_01_sma_daily --check
./strategy.sh example_weights_01_sma_daily --check
To run repository tests:
pytest -q
pytest -q
You can also run all strategies sequentially:
export QJ_API_KEY="YOUR_API_KEY"
./strategy.sh --all --output ./reports
export QJ_API_KEY="YOUR_API_KEY"
./strategy.sh --all --output ./reports
The batch launcher continues even if an individual strategy fails. It also generates individual logs and a batch summary.
For Windows users, the repository provides strategy.bat as an alternative to the shell launcher.
10. What QuantJourney Backtester Is Not
It’s important to understand the project’s boundaries.
QuantJourney Backtester is:
- Not a broker.
- Not a live trading system.
- Not an investment adviser.
- Not a guarantee of future profitability.
Some examples also simplify assumptions around borrowing costs, financing, liquidity, and market impact.
The goal is to make these assumptions visible so researchers can inspect and adjust them.
Also, while local strategy execution, accounting, reports, and CSV input can remain offline, the optional hosted market-data preparation workflow requires authentication.
GitHub: https://github.com/QuantJourneyOrg/quantjourney-bt
PyPI: https://pypi.org/project/quantjourney-bt/

