A comprehensive quantitative trading and market analysis platform featuring multi-factor models, technical indicators, pattern recognition, sentiment analysis, and backtesting capabilities.
- Multi-Factor Model: Advanced machine learning models (XGBoost, LightGBM, CatBoost, Random Forest) for stock selection and prediction
- Technical Indicators: Comprehensive technical analysis signals (RSI, MACD, CCI, Bollinger Bands, etc.)
- Pattern Recognition: Automated pattern detection (Head & Shoulders, Double Tops/Bottoms, Triangles, etc.)
- Sentiment Analysis: News sentiment analysis using FinBERT and RSS feeds
- Backtesting Engine: Robust backtesting framework with transaction costs, slippage, and performance metrics
- Factor Engineering: Custom factor generation and preprocessing (Winsorization, Z-score normalization, industry neutralization)
- Data Management: Efficient data loading and caching with PostgreSQL integration
multifactor/: Multi-factor model implementation with modular architecturebacktester/: Backtesting engine for strategy evaluationsignals/: Technical signals and pattern recognitionfactor/: Factor generation and engineeringutil/: Data loading utilities for stocks, crypto, and newsnews/: News sentiment analysis from RSS feedsother_strategy/: Additional trading strategies and alerts
- Python 3.8+
- PostgreSQL (for data caching)
- API Keys:
- Tiingo API (for stock/crypto data)
- Finnhub API (for fundamental data)
- Hugging Face API (for FinBERT sentiment analysis)
-
Clone the repository
git clone https://github.com/Joe251/QuantMarketLab.git cd QuantMarketLab -
Create a virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Install TA-Lib (if not already installed)
# macOS brew install ta-lib pip install TA-Lib # Linux wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz tar -xzf ta-lib-0.4.0-src.tar.gz cd ta-lib/ ./configure --prefix=/usr make sudo make install pip install TA-Lib
-
Set up PostgreSQL database
- Install PostgreSQL
- Create a database named
postgres(or updatedb_paramsin code) - Update database connection parameters in
app.pyand other files
-
Configure API keys
- Update API tokens in relevant files:
- Tiingo API token
- Finnhub API key
- Hugging Face token (for FinBERT)
- Update API tokens in relevant files:
QuantMarketLab/
├── app.py # Flask API server
├── multi_factor.py # Main multi-factor model wrapper
├── multifactor/ # Multi-factor model modules
│ ├── data_manager.py # Data loading and management
│ ├── model_manager.py # Model training and management
│ ├── preprocessor.py # Factor preprocessing
│ ├── backtester.py # Multi-factor backtesting
│ └── multifactor_model.py # Main orchestrator
├── backtester/ # Backtesting engine
│ └── backtest.py # Strategy backtesting functions
├── signals/ # Technical signals
│ ├── tech_sig.py # Technical indicators
│ ├── pattern_sig.py # Pattern recognition
│ └── elliottwave_sig.py # Elliott Wave analysis
├── factor/ # Factor generation
│ ├── factor_engine.py # Factor computation engine
│ └── factor_generator.py # Factor generation functions
├── util/ # Utilities
│ ├── stock/ # Stock data loading
│ ├── crypto/ # Crypto data loading
│ └── news/ # News data and analysis
├── news/ # RSS sentiment analysis
├── data/ # Data storage
│ └── stock_metrics/ # Stock metrics data
├── models/ # Trained models storage
└── logs/ # Application logs
python app.pyThe API server will start on http://localhost:5000 (or the configured port).
from multi_factor import train_and_backtest_multifactormodel
# Train and backtest a multi-factor model
results = train_and_backtest_multifactormodel(
load_fromcsv=True,
train_model=True,
train_startdate='2015-01-01',
test_startdate='2019-01-01',
train_enddate='2020-01-01',
backtest_startdate='2020-01-02',
backtest_enddate=None,
rebalance_period=5,
top_n=10
)from backtester import backtest_signal_strategy, plot_backtest_results
from signals.pattern_sig import PatternRecognizer
from util.stock.load_stock import load_stock_eodprice_from_tiingo
# Load data
df = load_stock_eodprice_from_tiingo('AAPL', '2021-01-01', '2023-12-31')
# Detect patterns
recognizer = PatternRecognizer('AAPL', df)
patterns_df = recognizer.analyze_all()
# Run backtest
df_backtest, summary, chart_data = backtest_signal_strategy(
df=df.join(patterns_df),
positive_signals_column=['positive_signal'],
negative_signals_column=['negative_signal'],
positive_signals_threshold=1,
negative_signals_threshold=1,
initial_capital=100000
)
# Plot results
plot_backtest_results(df_backtest, summary)POST /api/backtest- Run backtest for a given ticker
POST /api/multifactor/run- Train and backtest multi-factor model
GET /api/sentiment/stock- US stock market sentimentGET /api/sentiment/hkstock- Hong Kong stock market sentimentGET /api/sentiment/ashare- A-share market sentimentGET /api/sentiment/crypto- Crypto market sentiment
POST /api/news/analyze- Analyze company news sentiment
See app.py for complete API documentation.
The multi-factor model uses machine learning to predict stock returns based on multiple factors:
- Factor Preprocessing: Winsorization, cross-sectional Z-score normalization, industry/market cap neutralization
- Models: XGBoost, LightGBM, CatBoost, Random Forest, Gradient Boosting
- Backtesting: Rebalancing, turnover calculation, performance metrics (Sharpe ratio, drawdown, etc.)
A flexible factor computation engine supporting:
- Time-series functions (Ref, Delta, Mean, Std, etc.)
- Cross-sectional functions (CSRank, CSZScore, etc.)
- Technical indicators (RSI, MACD, CCI, etc.)
- Custom factor expressions
Automated detection of chart patterns:
- Head & Shoulders
- Double Tops/Bottoms
- Triangles (Ascending, Descending, Symmetrical)
- Flags and Pennants
- And more...
- Stock Data: Tiingo API
- Crypto Data: Tiingo API
- Fundamental Data: Finnhub API
- News Data: Tiingo News API, RSS feeds
- Sentiment Analysis: FinBERT (Hugging Face)
Update configuration in relevant files:
- Database:
db_paramsinapp.pyand data loading modules - API Tokens: Update tokens in respective modules
- Model Directory: Default
models/ - Data Directory: Default
data/
- Ensure PostgreSQL is running and accessible
- API keys are required for data fetching
- Large datasets are cached in PostgreSQL for faster access
- Model files are saved in
models/directory - Logs are written to
logs/directory
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
This software is for educational and research purposes only. It is not intended as financial advice. Trading involves risk, and past performance does not guarantee future results. Always do your own research and consult with a qualified financial advisor before making investment decisions.
For questions or support, please open an issue on GitHub.
Made with ❤️ for quantitative trading enthusiasts