A production-grade algorithmic trading platform featuring vectorized backtesting, Monte Carlo risk analysis, and Interactive Brokers integration. Built for quantitative researchers and systematic traders.
- π Vectorized Backtesting Engine - Pandas-based strategy simulation with nanosecond-level precision
- π² Risk Management Suite - Numba-accelerated Monte Carlo simulations with VaR/CVaR metrics
- β‘ Live Trading Gateway - Seamless integration with Interactive Brokers TWS API
- π Performance Analytics - Interactive Plotly dashboards with 30+ financial metrics
- π Parameter Optimization - Genetic algorithm-based hyperparameter tuning
- π Data Pipeline - Built-in support for Yahoo Finance, Polygon.io, and custom CSV formats
trading-platform/
βββ config/ # Strategy configuration files
βββ docs/ # Documentation & architecture diagrams
βββ src/
β βββ core/ # Backtesting engine and data models
β βββ risk_management/ # Monte Carlo simulations and risk metrics
β βββ live_trading/ # IB API integration layer
β βββ visualization/ # Performance dashboards
βββ tests/ # Unit and integration tests
βββ strategies/ # Example strategy implementations
[parameters]
entry_threshold = 0.02
exit_threshold = -0.01
lookback_period = 14
[risk]
max_drawdown = 0.15
position_size = 0.1
monte_carlo_sims = 1000
[data]
symbols = ["AAPL", "MSFT", "GOOG"]
start_date = "2020-01-01"
end_date = "2023-01-01"
from src.core import VectorizedBacktester
class MomentumStrategy(VectorizedBacktester):
def calculate_signals(self):
returns = self.data['close'].pct_change(self.params['lookback_period'])
self.signals = pd.DataFrame({
'long': returns > self.params['entry_threshold'],
'short': returns float:
"""
Calculate 95% VaR using Monte Carlo simulation
Parameters:
returns (np.ndarray): Historical daily returns
simulations (int): Number of MC simulations
time_horizon (int): Projection period in days
Returns:
float: Value at Risk (95% confidence)
"""
results = np.empty(simulations)
for i in range(simulations):
random_returns = np.random.choice(returns, size=time_horizon)
results[i] = np.prod(1 + random_returns) - 1
return np.percentile(results, 5)
def calculate_sharpe(returns: pd.Series,
risk_free_rate: float = 0.0) -> float:
excess_returns = returns - risk_free_rate/252
return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
def max_drawdown(equity_curve: pd.Series) -> float:
peak = equity_curve.expanding().max()
trough = equity_curve.expanding().min()
return (trough - peak).min()
from ib_insync import IB, MarketOrder, LimitOrder
class LiveTradingSession:
def __init__(self, strategy_config: dict):
self.ib = IB()
self.ib.connect('127.0.0.1', 7497, clientId=1)
def execute_order(self, contract, quantity, order_type, limit_price=None):
if order_type == 'market':
order = MarketOrder('BUY', quantity)
else:
order = LimitOrder('BUY', quantity, limit_price)
trade = self.ib.placeOrder(contract, order)
return trade
-
Start the development environment:
docker-compose up -d
-
Access the services:
- Application: http://localhost:8000
- Grafana: http://localhost:3000 (admin/admin)
- Prometheus: http://localhost:9091
- Drift Detection: http://localhost:8080
-
Prepare the environment:
# Set OpenStack credentials source openrc.sh # Create configuration archive tar czf config.tar.gz config/
-
Deploy using Heat:
openstack stack create -t deploy/openstack/stratvector.hot \ -e deploy/openstack/parameters.yaml \ stratvector-stack
-
Update deployment:
# Update configuration tar czf config.tar.gz config/ # Update stack openstack stack update -t deploy/openstack/stratvector.hot \ -e deploy/openstack/parameters.yaml \ stratvector-stack
-
Add required repositories:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts helm repo add grafana https://grafana.github.io/helm-charts helm repo update
-
Install dependencies:
helm install prometheus prometheus-community/kube-prometheus-stack
-
Install StratVector:
helm install stratvector deploy/kubernetes/stratvector
-
Upgrade deployment:
helm upgrade stratvector deploy/kubernetes/stratvector
- Python 3.7+
- Interactive Brokers Gateway (for live trading)
- TA-Lib (recommended for technical indicators)
# Clone repository
git clone https://github.com/hreger/stratvector
cd stratvector
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install with core dependencies
pip install -e ".[dev]"
The application exposes the following metrics:
process_resident_memory_bytes: Memory usageorder_latency_seconds: Order execution latencystrategy_drift_score: Strategy drift detection score
Configured alerts include:
- High memory usage (>1GB for 5 minutes)
- High order latency (>1 second for 1 minute)
- Strategy drift detected (score >0.8 for 5 minutes)
Pre-configured dashboards:
-
System Overview
- Memory usage
- CPU usage
- Network I/O
-
Trading Performance
- Order latency
- Execution success rate
- PnL tracking
-
Strategy Monitoring
- Drift detection scores
- Signal distribution
- Position sizes
The drift detection service runs every 6 hours and monitors:
- Feature distribution changes
- Performance degradation
- Market regime shifts
Results are available in Grafana and can trigger alerts.
-
Daily:
- Review performance metrics
- Check system logs
- Verify market data
-
Weekly:
- Performance analysis
- Strategy review
- Risk assessment
-
Monthly:
- Strategy optimization
- Parameter review
- System upgrade
-
System Shutdown:
# Kubernetes kubectl scale deployment stratvector --replicas=0 # Docker Compose docker-compose down
-
Data Backup:
# Backup configuration tar czf config_backup.tar.gz config/ # Backup data tar czf data_backup.tar.gz data/
- Fork the repository
- Create feature branch (
git checkout -b feature/awesome-feature) - Commit changes with semantic messages (
feat: Add neural strategy) - Push to branch (
git push origin feature/awesome-feature) - Open Pull Request with detailed description
Distributed under the MIT License. See LICENSE for more information.
Project Maintainer: [P Sanjeev Pradeep] - clashersanjeev@gmail.com
Project Link: https://github.com/hreger/stratvector
- Pandas for vectorized operations
- Numba for JIT acceleration
- IB-insync for Interactive Brokers API
- Plotly for interactive visualization
Made with β€οΈ for the quant community by P Sanjeev Pradeep