A comprehensive machine learning pipeline combining sentiment analysis and technical analysis for robust financial decision-making and swing trading.
This project combines two complementary models for comprehensive financial analysis:
- Unified investor sentiment signals from multiple data sources
- Kaggle Twitter dataset as core foundation
- FinancialBERT sentiment analysis for news headlines
- Google Trends alignment for interest tracking
- Machine learning training and backtesting capabilities
- Candlestick pattern recognition for technical analysis
- Optimized for 17.1 GB RAM with memory management
- Progressive training with 4-stage optimization
- Real-time trading signals with risk management
- Swing trading focus (1-3 day holding periods)
cd "price model"
python launch.py# Build dataset
python main.py --mode data
# Progressive training (optimized)
python main.py --mode progressive --experiment-name my_experiment
# Predict patterns
python main.py --mode predict --ticker AAPL
# Generate trading signals
python main.py --mode signals --portfolio AAPL MSFT GOOGL
# Complete demo
python main.py --mode demo| Stage | Batch Size | Memory Usage | Improvement |
|---|---|---|---|
| Stage 1 | 512 | 0.06 GB | 2x larger |
| Stage 2 | 256 | 0.05 GB | 4x larger |
| Stage 3 | 128 | 0.05 GB | 4x larger |
| Stage 4 | 64 | 0.05 GB | 4x larger |
- Build and prepare dataset
- Memory-optimized data loading
- Automatic feature normalization
- Standard single-stage training
- Optimized batch size (512)
- Enhanced logging and monitoring
- 4-stage progressive training
- Optimized batch sizes for each stage
- Memory management between stages
- Automatic model checkpointing
- Pattern prediction for any ticker
- Automatic model selection
- Confidence scoring
- Generate trading signals for portfolios
- Multi-stock analysis
- Signal strength ranking
- Complete pipeline demonstration
- Data โ Training โ Prediction โ Signals
- Run complete pipeline
- End-to-end processing
- Kaggle Twitter Dataset: Pre-existing high-quality Twitter sentiment data (core)
- NewsAPI: Real-time news headlines with FinancialBERT sentiment analysis
- Google Trends: Interest scores aligned with Twitter dataset dates/tickers
- Market Data: Stock prices for target variable creation
- Domain-specific sentiment analysis for financial text
- Model:
ahmedrachid/FinancialBERT-Sentiment-Analysis - Outputs: sentiment scores (-1 to 1), labels, and confidence scores
- All data sources aligned by date and ticker
- Kaggle dataset serves as the foundation
- Supporting features appended without disrupting original schema
- Lagged features (1, 3, 7 days)
- Moving averages (3, 7, 14 days)
- Momentum indicators
- Volatility measures
- 1-3 day holding periods - Perfect for swing trading
- 65 features per timestep - Comprehensive technical analysis
- Binary classification - Buy/Sell signals with confidence scores
- Risk management - Stop loss and take profit recommendations
- Incremental updates - Only collect recent data for existing tickers
- Graceful interruption - Press Ctrl+C to stop and save progress
- Backup protection - Automatic backup files during processing
- S&P 500 coverage - 500 stocks with quality filtering
- Integrated quality fixes - Automatic NaN handling, outlier detection, class balancing
- CNN architecture - Deep learning for pattern recognition
- Attention mechanism - Focus on important features
- Residual connections - Better gradient flow
- Progressive training - Two-stage training for better performance
- Real-time predictions - Get BUY/SELL signals for any stock
- Technical confirmation - RSI, MACD, moving averages
- Entry/Exit points - Optimal prices with stop loss/take profit
- Portfolio analysis - Compare multiple stocks at once
Financial Sentiment Model/
โโโ README.md # ๐ This comprehensive guide
โโโ sentiment model/ # ๐ง Sentiment analysis pipeline
โ โโโ README.md # ๐ Sentiment model documentation
โ โโโ src/
โ โ โโโ data/ # ๐ Data ingestion and processing
โ โ โโโ features/ # ๐ง Normalization + signal fusion
โ โ โโโ models/ # ๐ง ML training + evaluation
โ โ โโโ backtest/ # ๐ Backtesting strategies
โ โโโ data/
โ โ โโโ raw/ # ๐ Raw data (news, trends, market)
โ โ โโโ processed/ # ๐ Structured sentiment scores
โ โโโ configs/ # โ๏ธ Configuration files
โโโ price model/ # ๐ Technical analysis pipeline
โ โโโ main.py # ๐ฏ Main pipeline script
โ โโโ launch.py # ๐ Interactive launcher
โ โโโ memory_optimization.py # ๐พ Memory analysis tool
โ โโโ README_STREAMLINED.md # ๐ Streamlined documentation
โ โโโ src/
โ โ โโโ training/
โ โ โ โโโ train.py # ๐ง Streamlined training
โ โ โ โโโ progressive_trainer.py # ๐ Optimized progressive training
โ โ โโโ models/
โ โ โ โโโ dataset.py # ๐พ Memory-optimized data loading
โ โ โโโ ...
โ โโโ config/
โ โ โโโ config.json # โ๏ธ Optimized configuration
โ โโโ models/ # ๐ง Saved models
โ โโโ logs/ # ๐ Training logs
โ โโโ data/ # ๐ Dataset files
โโโ docs/ # ๐ Additional documentation
cd "price model"
python launch.py
# Choose from menu options# Quick progressive training
python main.py --mode progressive
# Custom experiment
python main.py --mode progressive --experiment-name my_experiment
# Predict specific stock
python main.py --mode predict --ticker TSLA
# Portfolio analysis
python main.py --mode signals --portfolio AAPL MSFT GOOGL TSLA AMZNcd "sentiment model"
# Complete pipeline
python src/data/backfill_historical_new.py \
--kaggle_path path/to/kaggle_twitter_sentiment.csv \
--tickers AAPL MSFT GOOGL TSLA \
--since 2023-01-01 \
--until 2023-12-31
# Individual components
python src/data/ingest_kaggle_twitter.py --kaggle_path dataset.csv
python src/data/ingest_news_financialbert.py --tickers AAPL TSLA
python src/data/ingest_trends_aligned.py --tickers AAPL TSLA- 2-4x faster training with larger batch sizes
- Better GPU utilization with optimized memory usage
- Stable convergence with more stable gradients
- Memory efficient using only 0.6% of available RAM
- Automatic cleanup between training stages
- No API Rate Limits: Uses pre-existing Twitter data
- Domain-Specific Sentiment: FinancialBERT for financial text
- Reliable Data Sources: Focused on News + Trends
- Modular Design: Run components independently
- Feature Rich: Comprehensive sentiment signals
- Maintainable: Clean, documented codebase
- โ Explicit data types (float32) to prevent object arrays
- โ Memory management between training stages
- โ Garbage collection and CUDA cache clearing
- โ Cached data loaders to prevent multiple instances
- โ Optimized batch sizes for 17.1 GB RAM
- โ Robust error handling and graceful failures
- Training Speed: 2-4x faster with optimized batch sizes
- Memory Usage: Only 0.6% of available RAM per stage
- Model Quality: Better convergence with larger batches
- Reliability: Robust error handling and recovery
- Unified Signals: Combined sentiment from multiple sources
- Domain Expertise: FinancialBERT for financial text analysis
- Feature Rich: Comprehensive sentiment indicators
- Scalable: Modular design for easy expansion
- Internet required: Downloads data from various sources
- Time intensive: Processing takes 2-4 hours for full datasets
- Graceful interruption: Press Ctrl+C to stop safely
- Backup protection: Automatic backup files created
- Quality improvements: Applied automatically by default
- GPU recommended: CUDA support for faster training
- Memory intensive: 16GB+ RAM recommended
- Patience required: Training takes 1-2 hours
- Early stopping: Prevents overfitting
- Not financial advice: Use at your own risk
- Backtesting recommended: Test on historical data
- Risk management: Always use stop losses
- Diversification: Don't put all money in one signal
Data Collection Fails:
# Check internet connection
# Verify API keys (if using paid data)
# Try incremental mode
python main.py --mode data --incrementalTraining Stuck:
# Reduce learning rate
# Increase patience
# Check GPU memory
python main.py --mode train --epochs 30Low Accuracy:
# Try progressive training
# Increase model capacity
# Check data quality
python main.py --mode train --epochs 75For Faster Training:
- Use GPU with CUDA
- Increase batch size (if memory allows)
- Reduce number of tickers for testing
For Better Accuracy:
- Use progressive training
- Increase training epochs
- Collect more recent data
- Use quality-improved dataset
- Technical Analysis: TA-Lib library
- Data Source: Yahoo Finance via yfinance
- Deep Learning: PyTorch framework
- S&P 500 Data: DataHub constituents
- FinancialBERT: Domain-specific sentiment analysis
- Kaggle Dataset: Twitter sentiment for financial markets
- โ Reorganized Structure: Moved scripts to appropriate folders
- โ Eliminated Redundancy: Removed duplicate files and scripts
- โ Documentation Consolidation: All docs organized properly
- โ Utility Scripts: Organized utility functions
- โ Quality Integration: Data quality fixes integrated into main pipeline
- โ Optimized Batch Sizes: 512, 256, 128, 64 for 17.1 GB RAM
- โ Memory Management: Between training stages
- โ Data Type Optimization: float32 to prevent object arrays
- โ Cached Data Loaders: Prevent multiple instances
- โ Interactive Launcher: Easy-to-use menu system
- โ Unified Commands: Single main.py handles all modes
- โ Comprehensive Documentation: All information in one place
- โ Error Handling: Robust error recovery
This project is for educational purposes. Use trading signals at your own risk.
The pipeline is now streamlined and optimized for your system. Simply run:
cd "price model"
python launch.pyOr start with:
python main.py --mode demoEverything is integrated, optimized, and ready to use! ๐ฏ