Skip to main content

An event-driven backtesting and execution simulation engine for quantitative trading strategies.

Project description

๐Ÿš€ QuantSim: Professional Event-Driven Backtesting Framework

Tests PyPI Python License Coverage Documentation

QuantSim is a modern, event-driven backtesting framework for quantitative trading strategies. Built with Python 3.9+, it provides institutional-grade simulation capabilities with a focus on performance, accuracy, and extensibility.

โœจ Why QuantSim?

  • ๐Ÿ—๏ธ Event-Driven Architecture: Realistic simulation that processes market events chronologically
  • ๐Ÿ“Š Multiple Data Sources: Yahoo Finance, CSV files, synthetic data generation
  • โšก High Performance: Optimized for speed with comprehensive caching and vectorized operations
  • ๐Ÿงช Battle-Tested: 178 unit tests with 95%+ coverage ensuring reliability
  • ๐Ÿ”ง Highly Extensible: Plugin architecture for strategies, indicators, and execution models
  • ๐Ÿ“ˆ Professional Reporting: Rich markdown reports with equity curves and performance metrics
  • ๐Ÿค– ML Integration: Optional machine learning components for advanced strategies
  • ๐Ÿ›ก๏ธ Production Ready: Comprehensive error handling, logging, and validation

๐Ÿ“ฆ Quick Installation

From PyPI (Recommended)

# Core package
pip install quantsim

# With ML capabilities
pip install quantsim[ml]

# With pairs trading (requires statsmodels)
pip install quantsim[pairs]

# Full installation with all features
pip install quantsim[ml,pairs]

For Development

git clone https://github.com/yash-tr/quantsim.git
cd quantsim
pip install -e .[dev]

๐Ÿš€ Quick Start

1. Simple Strategy Backtest

import quantsim as qs

# Create and run a simple SMA crossover strategy
engine = qs.SimulationEngine(
    data_source='yahoo',
    symbols=['AAPL'],
    start_date='2022-01-01',
    end_date='2023-01-01',
    strategy='sma_crossover',
    initial_capital=100000
)

results = engine.run()
print(f"Total Return: {results.total_return:.2%}")
print(f"Sharpe Ratio: {results.sharpe_ratio:.2f}")

2. Command Line Interface

# Run a single backtest
quantsim run --strategy sma_crossover --symbol AAPL --start 2022-01-01 --end 2023-01-01

# Batch backtesting from YAML config
quantsim batch my_strategies.yaml

# Get help
quantsim --help

3. Custom Strategy Development

from quantsim.strategies import Strategy
from quantsim.core.events import OrderEvent

class MyStrategy(Strategy):
    def __init__(self, symbols, **kwargs):
        super().__init__(symbols, **kwargs)
        self.window = kwargs.get('window', 20)
    
    def on_market_event(self, event):
        # Your strategy logic here
        if self.should_buy(event.symbol):
            order = OrderEvent(
                symbol=event.symbol,
                order_type='MKT',
                quantity=100,
                direction='BUY'
            )
            self.event_queue.put(order)
    
    def should_buy(self, symbol):
        # Implement your buy logic
        return True

๐Ÿ—๏ธ Core Features

Event-Driven Simulation Engine

  • Realistic Order Processing: Market, limit, and stop orders with configurable slippage
  • Portfolio Management: Real-time P&L tracking, risk metrics, and position management
  • Execution Simulation: Latency modeling, partial fills, and commission structures

Built-in Strategies

  • SMA Crossover: Moving average crossover with customizable windows
  • Momentum: Trend-following strategy with momentum indicators
  • Mean Reversion: Statistical arbitrage based on price deviations
  • Pairs Trading: Cointegration-based pairs trading (requires statsmodels)
  • ML Strategies: Integration with scikit-learn and TensorFlow

Data Sources

  • Yahoo Finance: Automatic data fetching with symbol validation
  • CSV Files: Flexible parser supporting multiple formats
  • Synthetic Data: Configurable data generation for testing

Advanced Analytics

  • Performance Metrics: Sharpe ratio, Sortino ratio, maximum drawdown, VaR
  • Trade Analysis: Win rate, profit factor, average trade duration
  • Risk Metrics: Beta, alpha, tracking error, information ratio
  • Visualizations: Equity curves, drawdown plots, trade distributions

๐Ÿ“Š Performance Metrics

QuantSim calculates comprehensive performance metrics:

Metric Description
Total Return Cumulative return over the backtest period
CAGR Compound Annual Growth Rate
Sharpe Ratio Risk-adjusted return measure
Sortino Ratio Downside deviation-adjusted returns
Maximum Drawdown Largest peak-to-trough decline
Calmar Ratio CAGR divided by maximum drawdown
Win Rate Percentage of profitable trades
Profit Factor Ratio of gross profits to gross losses

๐Ÿ› ๏ธ Architecture Overview

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Data Handler   โ”‚โ”€โ”€โ”€โ–ถโ”‚ Event Queue  โ”‚โ”€โ”€โ”€โ–ถโ”‚  Strategy   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚                      โ”‚
                              โ–ผ                      โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Portfolio     โ”‚โ—€โ”€โ”€โ”€โ”‚   Engine     โ”‚โ—€โ”€โ”€โ”€โ”‚   Orders    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚
                              โ–ผ
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚  Execution   โ”‚
                    โ”‚   Handler    โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ“ˆ Example Strategies

SMA Crossover Strategy

from quantsim import SMACrossoverStrategy

strategy = SMACrossoverStrategy(
    symbols=['AAPL', 'GOOGL'],
    short_window=10,
    long_window=30,
    event_queue=event_queue
)

Custom ML Strategy

from quantsim.strategies.ml import MLStrategy
from sklearn.ensemble import RandomForestClassifier

strategy = MLStrategy(
    symbols=['SPY'],
    model=RandomForestClassifier(),
    features=['sma_10', 'rsi_14', 'macd'],
    lookback_window=60
)

๐Ÿงช Testing & Quality

QuantSim maintains high code quality standards:

  • 178 Unit Tests with 95%+ coverage
  • Multi-platform Testing (Ubuntu, Windows, macOS)
  • Python 3.9+ Support across versions
  • Automated CI/CD with GitHub Actions
  • Code Quality Checks (Black, Flake8, MyPy)
  • Security Scanning (Bandit, Safety)
# Run tests locally
pytest tests/ -v --cov=quantsim

# Generate coverage report
pytest --cov=quantsim --cov-report=html

๐Ÿ“š Documentation & Examples

Available Resources

Example Configurations

# sample_batch_config.yaml
strategies:
  - name: "SPY_SMA_Crossover"
    strategy: "sma_crossover"
    data_source: "yahoo"
    symbols: ["SPY"]
    start_date: "2020-01-01"
    end_date: "2023-01-01"
    short_window: 10
    long_window: 30
    initial_capital: 100000

๐Ÿš€ Advanced Usage

Batch Processing

# Run multiple strategies from YAML config
quantsim batch strategies.yaml --output-dir results/

# Parallel execution
quantsim batch strategies.yaml --parallel --workers 4

Custom Indicators

from quantsim.indicators import Indicator

class RSI(Indicator):
    def __init__(self, period=14):
        self.period = period
    
    def calculate(self, prices):
        # RSI calculation logic
        return rsi_values

Risk Management

from quantsim.risk import RiskManager

risk_manager = RiskManager(
    max_position_size=0.1,  # 10% max position
    max_drawdown=0.05,      # 5% max drawdown
    var_limit=0.02          # 2% VaR limit
)

๐ŸŒŸ Competitive Advantages

Feature QuantSim Zipline Backtrader FreqTrade
Modern Python โœ… 3.9+ โŒ 3.6+ โœ… 3.7+ โœ… 3.8+
Event-Driven โœ… โœ… โŒ โœ…
ML Integration โœ… โŒ โŒ โœ…
Multi-Asset โœ… โœ… โœ… โŒ
Real-time Ready โœ… โŒ โœ… โœ…
Professional Reports โœ… โŒ โŒ โœ…

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Quick Contribution Steps

  1. ๐Ÿด Fork the repository
  2. ๐Ÿ”„ Clone your fork: git clone https://github.com/yourusername/quantsim.git
  3. ๐ŸŒฟ Create a branch: git checkout -b feature/amazing-feature
  4. โœจ Make your changes and add tests
  5. โœ… Run tests: pytest tests/
  6. ๐Ÿ“ Commit: git commit -m "Add amazing feature"
  7. ๐Ÿš€ Push: git push origin feature/amazing-feature
  8. ๐Ÿ”„ Create a Pull Request

Development Setup

git clone https://github.com/yash-tr/quantsim.git
cd quantsim
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -e .[dev]
pre-commit install  # Optional: setup pre-commit hooks

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Acknowledgments


๐Ÿ“ž Support & Community


๐Ÿ—บ๏ธ Roadmap

Version 0.2.0 (Coming Soon)

  • ๐Ÿ”„ Real-time trading integration
  • ๐Ÿ“Š Advanced portfolio optimization
  • ๐ŸŒ WebSocket data feeds
  • ๐Ÿ“ฑ Interactive dashboard

Version 0.3.0 (Future)

  • ๐Ÿค– AutoML strategy generation
  • โ˜๏ธ Cloud deployment options
  • ๐Ÿ“ˆ Options and derivatives support
  • ๐Ÿ”— Crypto exchange integration

Ready to transform your trading strategies? Install QuantSim today and start building professional backtests in minutes!

pip install quantsim

โญ Star us on GitHub if QuantSim helps your trading! โญ

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

simquant-0.1.0.tar.gz (112.5 kB view details)

Uploaded Source

Built Distribution

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

simquant-0.1.0-py3-none-any.whl (86.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: simquant-0.1.0.tar.gz
  • Upload date:
  • Size: 112.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for simquant-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ff0b30d21c593e7dd3e8647feaa34065599172c31982642b93d3d0b2b03cdce1
MD5 490b351ca9ba25e0b53c9c18d70d9c6f
BLAKE2b-256 b71b159bed2e61d10b12400e6f1d82b478f91a3648750af0590b8cb510c52c4d

See more details on using hashes here.

Provenance

The following attestation bundles were made for simquant-0.1.0.tar.gz:

Publisher: publish-to-pypi.yml on yash-tr/quantsim

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

File details

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

File metadata

  • Download URL: simquant-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 86.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for simquant-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dd0fbd606e41967e848b39861c3795bf8bb46b42db734c1a2d3c82aeaa84af99
MD5 3274eca0e7e9ee8c05924a6f91f73f98
BLAKE2b-256 3b62fb1fc53b579eb2e5bed2558eea64c557abe082e5611bf3caf5709a717a5e

See more details on using hashes here.

Provenance

The following attestation bundles were made for simquant-0.1.0-py3-none-any.whl:

Publisher: publish-to-pypi.yml on yash-tr/quantsim

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