Skip to main content

Simple backtesting framework for trading strategies

Project description

Simple Backtest

Simple, high-performance backtesting framework for trading strategies. I created this library so anyone can implement their own trading strategy with simple code, just create a new class that inherits from the Strategy class and implement the predict method and run the backtest on your data.

Features

  • 🚀 Parallel strategy execution
  • 📊 20+ performance metrics (Sharpe, Sortino, Calmar, etc.)
  • 📈 Interactive Plotly visualizations
  • 🎯 Clean Strategy Pattern architecture
  • 💰 Flexible commission models

Installation

# Using uv (recommended)
uv pip install simple-backtest

# Or with pip
pip install simple-backtest

Quick Start

import pandas as pd
from simple_backtest import BacktestConfig, Backtest
from simple_backtest.strategy.moving_average import MovingAverageStrategy
from simple_backtest.visualization.plotter import plot_equity_curve

# Load OHLCV data
data = pd.read_csv("data.csv", index_col=0, parse_dates=True)

# Configure backtest
config = BacktestConfig(
    initial_capital=10000.0,
    lookback_period=50,
    commission_type="percentage",
    commission_value=0.001,
)

# Run backtest
strategy = MovingAverageStrategy(short_window=10, long_window=30, shares=100)
backtest = Backtest(data=data, config=config)
results = backtest.run([strategy])

# Visualize
plot_equity_curve(results).show()

# Print metrics
print(results[strategy.get_name()]['metrics'])

Create Custom Strategy

from simple_backtest import Strategy

class MyStrategy(Strategy):
    def predict(self, data, trade_history):
        """
        :param data: OHLCV DataFrame
        :param trade_history: List of past trades
        :return: Dict with signal, size, order_ids
        """
        if data['Close'].iloc[-1] < 100:
            return {"signal": "buy", "size": 10, "order_ids": None}
        elif data['Close'].iloc[-1] > 120:
            return {"signal": "sell", "size": 10, "order_ids": None}
        return {"signal": "hold", "size": 0, "order_ids": None}

Notebooks

Check out the notebooks/ folder for interactive examples:

  • 01_basic_usage.ipynb: Introduction to the framework
  • 02_rsi_strategy.ipynb: RSI momentum strategy
  • 03_bollinger_bands_strategy.ipynb: Mean reversion with Bollinger Bands
  • 04_strategy_comparison.ipynb: Compare multiple strategies

To run the notebooks:

# Install with dev dependencies
uv sync --all-extras

# Start Jupyter
jupyter notebook

Development

# Clone repo
git clone <repo-url>
cd simple-backtest

# Install with uv
uv sync --all-extras

# Run tests
uv run pytest

# Lint
uv run ruff check simple_backtest

Metrics

  • Returns: Total Return, CAGR
  • Risk: Volatility, Sharpe, Sortino, Calmar, Max Drawdown
  • Trades: Win Rate, Profit Factor, Expectancy
  • Benchmark: Alpha, Beta, Information Ratio

Built-in Strategies

  • Buy and Hold: Simple baseline strategy
  • Moving Average Crossover: Trade on MA crossovers

See notebooks/ for more strategy examples (RSI, Bollinger Bands, etc.).

License

MIT

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

simple_backtest-0.1.0.tar.gz (25.6 kB view details)

Uploaded Source

Built Distribution

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

simple_backtest-0.1.0-py3-none-any.whl (30.2 kB view details)

Uploaded Python 3

File details

Details for the file simple_backtest-0.1.0.tar.gz.

File metadata

  • Download URL: simple_backtest-0.1.0.tar.gz
  • Upload date:
  • Size: 25.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for simple_backtest-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a431598ae581e40fb295088ab8a51e08bf56690480d0f68f7ea62331a3b3600b
MD5 2922f51497dd0437bfe93523353bd9ce
BLAKE2b-256 42836efce82070fb77b8643e6a805579af70792e01b7438d912f2ab299d437ea

See more details on using hashes here.

File details

Details for the file simple_backtest-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_backtest-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 67e0a7d31f1c18b261d2c0533204f2802b3665ef5791c597e4b6bdda389c3e7d
MD5 ca5aa49ac97345cbb5222a4646024825
BLAKE2b-256 8205fd030cb84842930c6fb6fd8817917637f4ff586a37e5c23020757afd4be3

See more details on using hashes here.

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