GG Quant is a powerful, modular framework for quantitative trading that combines traditional financial analysis with cutting-edge AI technologies including Large Language Models (LLMs) and Reinforcement Learning (RL).
- Multi-source Data: Support for Yahoo Finance, Tushare, and custom data sources
- SQLite Database: Efficient local storage and retrieval
- Technical Indicators: Built-in technical analysis (RSI, MACD, Bollinger Bands, etc.)
- Data Processing: Automated cleaning, validation, and feature engineering
- Multiple LLM Providers: Ollama (local), OpenAI, HuggingFace
- Free Model Support: Cost-effective analysis with local models
- Sentiment Analysis: Market sentiment extraction from text
- AI-Generated Insights: Automated market analysis and recommendations
- Trading Environment: Gymnasium-compatible trading environments
- Multiple Agents: Q-Learning, Deep Q-Networks, and more
- Custom Strategies: Train RL agents for specific trading scenarios
- Performance Evaluation: Comprehensive agent testing and comparison
- Strategy Library: Pre-built trading strategies (MA crossover, RSI, etc.)
- Performance Metrics: Comprehensive risk and return analysis
- Strategy Comparison: Multi-strategy performance comparison
- Custom Strategies: Easy strategy development framework
- Unit Tests: Comprehensive module testing
- Integration Tests: End-to-end workflow validation
- Performance Tests: System performance validation
pip install gg-quantgit clone https://github.com/ggquant/gg-quant.git
cd gg-quant
pip install -e ".[dev]"GG Quant requires Python 3.8+ and the following main dependencies:
pandas,numpy- Data analysisyfinance,tushare- Market datalangchain,ollama- LLM integrationgymnasium,stable-baselines3- Reinforcement learningmatplotlib,seaborn- Visualization
from gg_quant import DataManager
# Initialize data manager
data_manager = DataManager("data/my_portfolio.db")
# Fetch and store data
symbols = ["AAPL", "GOOGL", "MSFT"]
results = data_manager.fetch_and_store(symbols, period="1y")
# Retrieve processed data
aapl_data = data_manager.get_data("AAPL", start_date="2023-01-01")
print(aapl_data.head())from gg_quant import LLMAnalyzer
# Initialize with local Ollama model
analyzer = LLMAnalyzer("ollama")
# Analyze sentiment
sentiment = analyzer.analyze_sentiment("Apple stock is performing well today")
print(f"Sentiment: {sentiment}")
# Generate market insights
market_analysis = analyzer.analyze_market("AAPL", aapl_data, {"rsi": 45.2})
print(market_analysis["analysis"])
# Get trading signal
signal = analyzer.generate_signal("AAPL", aapl_data, strategy="technical")
print(f"Signal: {signal['signal']} (Confidence: {signal['confidence']})")from gg_quant import BacktestEngine
from gg_quant.backtest.strategies import MovingAverageStrategy
# Create strategy
strategy = MovingAverageStrategy(short_window=10, long_window=50)
# Run backtest
engine = BacktestEngine(initial_capital=10000)
result = engine.run_backtest(aapl_data, strategy)
# View results
print(f"Total Return: {result['metrics']['total_return']:.2%}")
print(f"Sharpe Ratio: {result['metrics']['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {result['metrics']['max_drawdown']:.2%}")from gg_quant import RLAgent
# Create RL agent
agent = RLAgent()
# Create trading environment
env = agent.create_environment(aapl_data, initial_balance=10000)
# Train agent
train_result = agent.train(total_timesteps=5000)
print(f"Training completed: {train_result}")
# Evaluate agent
eval_result = agent.evaluate(n_episodes=10)
print(f"Average reward: {eval_result['avg_reward']:.2f}")gg_quant/
βββ data/ # Data management
β βββ database/ # SQLite database management
β βββ fetchers/ # Data fetching from various sources
β βββ processors/ # Data processing and technical analysis
β βββ models/ # Data models and structures
βββ llm/ # LLM integration
β βββ clients/ # Various LLM client implementations
β βββ analyzers/ # AI-powered analysis tools
β βββ models/ # LLM configurations and templates
βββ rl/ # Reinforcement learning
β βββ environments/ # Trading environments
β βββ agents/ # RL agent implementations
β βββ trainers/ # Training utilities
βββ backtest/ # Backtesting system
β βββ engine/ # Core backtesting engine
β βββ metrics/ # Performance metrics
β βββ strategies/ # Trading strategies
βββ test/ # Testing framework
β βββ unit/ # Unit tests
β βββ integration/ # Integration tests
βββ utils/ # Utilities and helpers
Create a .env file in your project root:
# Tushare API (optional)
TUSHARE_TOKEN=your_tushare_token
# OpenAI API (optional)
OPENAI_API_KEY=your_openai_key
# HuggingFace API (optional)
HUGGINGFACE_API_KEY=your_huggingface_key
# Ollama configuration
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=gemma:2bfrom gg_quant.llm.models import LLMConfig, ModelRegistry
# Add custom model configuration
custom_config = LLMConfig(
name="custom_gpt",
provider="openai",
model_id="gpt-4",
api_key="your_key",
max_tokens=2000
)
registry = ModelRegistry()
registry.add_model(custom_config)- Moving Average Crossover: Classic MA strategy
- RSI Mean Reversion: RSI-based overbought/oversold strategy
- Bollinger Bands: Volatility-based breakout strategy
- MACD Strategy: Trend following using MACD crossovers
- Buy and Hold: Simple benchmark strategy
- Sentiment-Based: Trade based on news sentiment
- AI Signals: Use LLM-generated trading signals
- Hybrid: Combine technical and AI signals
Run the test suite:
# Run all tests
python -m pytest
# Run unit tests only
python -m pytest gg_quant/test/unit/
# Run integration tests only
python -m pytest gg_quant/test/integration/
# Run with coverage
python -m pytest --cov=gg_quantThe examples/ directory contains comprehensive examples:
basic_backtest.py- Simple backtesting examplerl_training.py- Train an RL trading agentai_analysis.py- Use LLM for market analysisdata_pipeline.py- Complete data processing pipeline
We welcome contributions! Please see our Contributing Guide for details.
git clone https://github.com/ggquant/gg-quant.git
cd gg-quant
pip install -e ".[dev]"
pre-commit installWe use:
- Black for code formatting
- Flake8 for linting
- MyPy for type checking
# Format code
black gg_quant/ tests/
# Run linting
flake8 gg_quant/ tests/
# Type checking
mypy gg_quant/Full documentation is available at gg-quant.readthedocs.io
- Web-based dashboard
- Real-time data streaming
- Options and derivatives support
- Portfolio optimization
- Advanced neural network architectures
- Multi-asset portfolio strategies
- Risk management tools
- Cloud deployment options
This project is licensed under the MIT License - see the LICENSE file for details.
- Gymnasium - RL environments
- LangChain - LLM integration
- Pandas - Data manipulation
- Stable-Baselines3 - RL algorithms
- yfinance - Market data
- Documentation: gg-quant.readthedocs.io
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Disclaimer: This software is for educational and research purposes only. Past performance is not indicative of future results. Always conduct your own research before making investment decisions.