An event-driven backtesting and execution simulation engine for quantitative trading strategies.
Project description
๐ QuantSim: Professional Event-Driven Backtesting Framework
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
- ๐ API Documentation - Complete API reference
- ๐ Jupyter Notebooks - Interactive examples and tutorials
- ๐ง Configuration Guide - Setup and configuration
- ๐ค Contributing Guide - How to contribute
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
- ๐ด Fork the repository
- ๐ Clone your fork:
git clone https://github.com/yourusername/quantsim.git - ๐ฟ Create a branch:
git checkout -b feature/amazing-feature - โจ Make your changes and add tests
- โ
Run tests:
pytest tests/ - ๐ Commit:
git commit -m "Add amazing feature" - ๐ Push:
git push origin feature/amazing-feature - ๐ 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
- Financial Data: Powered by yfinance
- Numerical Computing: Built on NumPy and Pandas
- Visualization: Charts generated with Matplotlib
- Testing: Quality assured with pytest
๐ Support & Community
- ๐ Bug Reports: GitHub Issues
- ๐ก Feature Requests: GitHub Discussions
- ๐ง Email: tripathiyash1004@gmail.com
- ๐ฌ Community: Join our discussions for tips, strategies, and support
๐บ๏ธ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ff0b30d21c593e7dd3e8647feaa34065599172c31982642b93d3d0b2b03cdce1
|
|
| MD5 |
490b351ca9ba25e0b53c9c18d70d9c6f
|
|
| BLAKE2b-256 |
b71b159bed2e61d10b12400e6f1d82b478f91a3648750af0590b8cb510c52c4d
|
Provenance
The following attestation bundles were made for simquant-0.1.0.tar.gz:
Publisher:
publish-to-pypi.yml on yash-tr/quantsim
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
simquant-0.1.0.tar.gz -
Subject digest:
ff0b30d21c593e7dd3e8647feaa34065599172c31982642b93d3d0b2b03cdce1 - Sigstore transparency entry: 232195652
- Sigstore integration time:
-
Permalink:
yash-tr/quantsim@85d7c09ecfa8f282d9f5775ff9a24caa09459fb0 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/yash-tr
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@85d7c09ecfa8f282d9f5775ff9a24caa09459fb0 -
Trigger Event:
workflow_dispatch
-
Statement type:
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dd0fbd606e41967e848b39861c3795bf8bb46b42db734c1a2d3c82aeaa84af99
|
|
| MD5 |
3274eca0e7e9ee8c05924a6f91f73f98
|
|
| BLAKE2b-256 |
3b62fb1fc53b579eb2e5bed2558eea64c557abe082e5611bf3caf5709a717a5e
|
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
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
simquant-0.1.0-py3-none-any.whl -
Subject digest:
dd0fbd606e41967e848b39861c3795bf8bb46b42db734c1a2d3c82aeaa84af99 - Sigstore transparency entry: 232195653
- Sigstore integration time:
-
Permalink:
yash-tr/quantsim@85d7c09ecfa8f282d9f5775ff9a24caa09459fb0 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/yash-tr
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@85d7c09ecfa8f282d9f5775ff9a24caa09459fb0 -
Trigger Event:
workflow_dispatch
-
Statement type: