Privacy-preserving agentic SLM for quant strategy forging
Project description
📈 QuantStratForge
Privacy-preserving agentic SLM for quant strategy forging
QuantStratForge is the first AI-powered quantitative strategy development platform that combines federated learning with privacy-preserving techniques to generate, backtest, and optimize trading strategies without compromising sensitive financial data.
🌟 Key Features
- 🤖 AI Strategy Generation: Generate trading strategies using advanced language models
- 🔒 Privacy-Preserving: Federated learning ensures your data never leaves your machine
- 📊 Comprehensive Backtesting: Built-in backtesting engine with performance metrics
- ⚡ Strategy Optimization: Automated parameter optimization for maximum returns
- 🌐 Multiple Interfaces: CLI, Streamlit web app, and FastAPI REST API
- 📈 Real-time Data: Integration with Yahoo Finance for live market data
- 🎯 Risk Management: Built-in risk assessment and portfolio optimization
🚀 Quick Start
Installation
pip install quantstratforge
Basic Usage
from quantstratforge import DataFetcher, StrategyGenerator, Backtester, Optimizer
# 1. Fetch market data
fetcher = DataFetcher()
data = fetcher.get_time_series("AAPL")
# 2. Generate AI strategy
generator = StrategyGenerator()
strategy = generator.generate(f"Market data for AAPL: {data}")
# 3. Backtest strategy
backtester = Backtester(ticker="AAPL")
results = backtester.backtest(strategy["strategy_code"])
# 4. Optimize parameters
optimizer = Optimizer(backtester)
optimized = optimizer.optimize(strategy["strategy_code"], {
"threshold": [0.01, 0.02, 0.03],
"period": [10, 15, 20]
})
print(f"Sharpe Ratio: {results['sharpe_ratio']:.3f}")
print(f"Best Parameters: {optimized['best_params']}")
🖥️ Demo Applications
Streamlit Web App
Interactive web interface for strategy development:
# Install demo dependencies
pip install quantstratforge[demo]
# Run Streamlit demo
streamlit run demos/streamlit_demo.py
FastAPI REST API
RESTful API for programmatic access:
# Run FastAPI demo
python demos/fastapi_demo.py
API Documentation: Visit http://localhost:8000/docs for interactive API documentation.
Command Line Interface
# Prepare training data
quantstratforge prepare
# Train model (local or federated)
quantstratforge train --federated
# Generate strategy
quantstratforge generate --ticker AAPL --news "Positive earnings outlook"
# Backtest strategy
quantstratforge backtest --strategy_code "def strategy_func(df): ..."
# Optimize strategy
quantstratforge optimize --strategy_code "..." --params '{"threshold": [0.01, 0.02]}'
🏗️ Architecture
Core Components
- DataFetcher: Handles market data acquisition and preprocessing
- StrategyModel: Manages AI model training (local and federated)
- StrategyGenerator: Generates trading strategies using trained models
- Backtester: Executes backtesting with performance analysis
- Optimizer: Optimizes strategy parameters for maximum returns
Federated Learning
QuantStratForge uses Flower (Federated Learning Framework) to enable collaborative model training:
# Federated training with multiple clients
model = StrategyModel()
model.federated_train(
num_clients=3,
num_rounds=5,
data_path="./formatted_data"
)
📊 Performance Metrics
Backtesting Results
- Sharpe Ratio: Risk-adjusted return metric
- Cumulative Returns: Total portfolio performance
- Maximum Drawdown: Largest peak-to-trough decline
- Win Rate: Percentage of profitable trades
- Volatility: Standard deviation of returns
Optimization Metrics
- Parameter Sensitivity: How strategy performance varies with parameters
- Convergence Speed: Time to find optimal parameters
- Robustness: Performance across different market conditions
🔧 Advanced Usage
Custom Strategy Development
def custom_strategy(df):
"""Custom trading strategy implementation"""
# Calculate technical indicators
df['MA_20'] = df['Close'].rolling(20).mean()
df['RSI'] = calculate_rsi(df['Close'])
# Generate signals
signals = (df['Close'] > df['MA_20']) & (df['RSI'] < 70)
return signals.astype(int)
# Backtest custom strategy
backtester = Backtester(ticker="AAPL")
results = backtester.backtest(custom_strategy)
Federated Learning Setup
# Configure federated learning
from quantstratforge.model import StrategyModel
model = StrategyModel(
model_name="mistralai/Mistral-7B-Instruct-v0.2",
lora_r=16
)
# Start federated training
model.federated_train(
num_clients=5,
num_rounds=10,
client_resources={"num_cpus": 2, "num_gpus": 0.5}
)
API Integration
import requests
# Generate strategy via API
response = requests.post("http://localhost:8000/api/generate-strategy", json={
"ticker": "AAPL",
"risk_level": "medium",
"news_sentiment": "Positive market sentiment"
})
strategy = response.json()
print(strategy["strategy_code"])
📈 Use Cases
Individual Traders
- Generate personalized trading strategies
- Backtest ideas before live trading
- Optimize parameters for maximum returns
- Learn quantitative trading concepts
Financial Institutions
- Develop proprietary trading algorithms
- Collaborate on model training without data sharing
- Scale strategy development across teams
- Maintain regulatory compliance
Research Organizations
- Study market behavior patterns
- Develop new quantitative methods
- Publish research with reproducible results
- Collaborate with industry partners
🔒 Privacy & Security
Data Protection
- Local Processing: All sensitive data stays on your machine
- Federated Learning: Models trained without sharing raw data
- Encryption: All communications encrypted in transit
- Audit Trail: Complete logging of all operations
Compliance
- GDPR: Full compliance with European data protection regulations
- SOX: Meets Sarbanes-Oxley requirements for financial data
- PCI DSS: Secure handling of financial information
- Custom: Configurable for specific regulatory requirements
🧪 Testing
Run the comprehensive test suite:
# Install development dependencies
pip install quantstratforge[dev]
# Run tests
pytest tests/ -v
# Run with coverage
pytest tests/ --cov=quantstratforge --cov-report=html
📚 Documentation
- API Reference
- Federated Learning Guide
- Strategy Development Tutorial
- Deployment Guide
- Contributing Guidelines
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Development Setup
# Clone repository
git clone https://github.com/your-username/quantstratforge.git
cd quantstratforge
# Install in development mode
pip install -e ".[dev,demo]"
# Run tests
pytest
# Format code
black .
ruff check . --fix
📄 License
This project is licensed under the Apache License 2.0. See LICENSE for details.
🆘 Support
- Documentation: https://quantstratforge.readthedocs.io
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: support@quantstratforge.com
🌟 Acknowledgments
- Hugging Face for transformer models
- Flower for federated learning framework
- Streamlit for web application framework
- FastAPI for REST API framework
- Yahoo Finance for market data
📊 Statistics
Made with ❤️ for the quantitative finance community
QuantStratForge - Where AI meets Privacy in Quantitative 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 quantstratforge-0.2.0.tar.gz.
File metadata
- Download URL: quantstratforge-0.2.0.tar.gz
- Upload date:
- Size: 16.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.14.0-33-generic
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fbf1494b24f788ce0b6ff9466fbcf656b87fe6b1bde9cedab41f470e35a22c77
|
|
| MD5 |
7c9642a0efeb98e6eec43935376837b0
|
|
| BLAKE2b-256 |
68bc520a60ded43aa49544e56b2cf5c35ed25c8bad7d7b8d1e824227d0db78fa
|
File details
Details for the file quantstratforge-0.2.0-py3-none-any.whl.
File metadata
- Download URL: quantstratforge-0.2.0-py3-none-any.whl
- Upload date:
- Size: 17.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.14.0-33-generic
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ec5e3b221659cfeedbb16a56e35aef221a5c8d4516d955f8dc4c4a153cd42b5e
|
|
| MD5 |
f870dd844b1d4b9cfc12128732ded5a1
|
|
| BLAKE2b-256 |
ef7cfb424e9d7ab4fd26856b1cbf0badf00c863bf77f1bb0b977db5e84ac094c
|