Skip to main content

Privacy-preserving agentic SLM for quant strategy forging

Project description

📈 QuantStratForge

PyPI version License: Proprietary Python 3.12+ Downloads

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

🤝 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 a Proprietary License. See LICENSE for details.

Commercial Use: Requires a royalty-based license. Contact vikkychoppa@gmail.com for licensing terms.

🆘 Support

🌟 Acknowledgments

📊 Statistics

GitHub stars GitHub forks GitHub issues GitHub pull requests


Made with ❤️ for the quantitative finance community

QuantStratForge - Where AI meets Privacy in Quantitative 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

quantstratforge-0.1.0.tar.gz (12.6 kB view details)

Uploaded Source

Built Distribution

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

quantstratforge-0.1.0-py3-none-any.whl (13.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: quantstratforge-0.1.0.tar.gz
  • Upload date:
  • Size: 12.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.14.0-28-generic

File hashes

Hashes for quantstratforge-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1417c8db31daf652cc3d418c0e9bca1e86b0cc51b38ef2b49d50b9dba1f5ce0f
MD5 6fe58252158528c28527f72abc188f7f
BLAKE2b-256 94dda6258a30a23b9793179e574fa7e9e67179f31416023e073671241343cd20

See more details on using hashes here.

File details

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

File metadata

  • Download URL: quantstratforge-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 13.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.14.0-28-generic

File hashes

Hashes for quantstratforge-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 159055ae5f210f8ed5077aa3dd9671148b3bcb6608a9ef6ca8e23d5ef78025cf
MD5 0ba87e70f57dfda73be00d0f472d24e7
BLAKE2b-256 97c7869ac22a71c5616765166ebfbf78014098dfb448b62db1d32d4cd589ae56

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