Skip to content

hopple/gg_quant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

GG Quant - Comprehensive Quantitative Trading Framework

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).

πŸš€ Features

πŸ“Š Data Management

  • 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

πŸ€– AI-Powered Analysis

  • 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

🧠 Reinforcement Learning

  • 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

πŸ“ˆ Backtesting System

  • 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

πŸ§ͺ Testing Framework

  • Unit Tests: Comprehensive module testing
  • Integration Tests: End-to-end workflow validation
  • Performance Tests: System performance validation

πŸ“¦ Installation

Quick Install

pip install gg-quant

Development Install

git clone https://github.com/ggquant/gg-quant.git
cd gg-quant
pip install -e ".[dev]"

Dependencies

GG Quant requires Python 3.8+ and the following main dependencies:

  • pandas, numpy - Data analysis
  • yfinance, tushare - Market data
  • langchain, ollama - LLM integration
  • gymnasium, stable-baselines3 - Reinforcement learning
  • matplotlib, seaborn - Visualization

🎯 Quick Start

1. Data Management

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())

2. AI-Powered Analysis

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']})")

3. Backtesting

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%}")

4. Reinforcement Learning

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}")

πŸ“ Project Structure

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

πŸ”§ Configuration

Environment Variables

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:2b

Custom Configuration

from 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)

πŸ“Š Available Strategies

Technical Analysis Strategies

  • 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

AI-Enhanced Strategies

  • Sentiment-Based: Trade based on news sentiment
  • AI Signals: Use LLM-generated trading signals
  • Hybrid: Combine technical and AI signals

πŸ§ͺ Testing

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_quant

πŸ“ˆ Examples

The examples/ directory contains comprehensive examples:

  • basic_backtest.py - Simple backtesting example
  • rl_training.py - Train an RL trading agent
  • ai_analysis.py - Use LLM for market analysis
  • data_pipeline.py - Complete data processing pipeline

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/ggquant/gg-quant.git
cd gg-quant
pip install -e ".[dev]"
pre-commit install

Code Style

We 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/

πŸ“š Documentation

Full documentation is available at gg-quant.readthedocs.io

API Documentation

Tutorials

πŸ—ΊοΈ Roadmap

Version 1.1 (Planned)

  • Web-based dashboard
  • Real-time data streaming
  • Options and derivatives support
  • Portfolio optimization

Version 1.2 (Planned)

  • Advanced neural network architectures
  • Multi-asset portfolio strategies
  • Risk management tools
  • Cloud deployment options

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Gymnasium - RL environments
  • LangChain - LLM integration
  • Pandas - Data manipulation
  • Stable-Baselines3 - RL algorithms
  • yfinance - Market data

πŸ“ž Support

⭐ Star History

Star History Chart


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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages