A professional machine learning toolkit for financial data analysis. This project demonstrates production-quality Python engineering for quantitative finance, featuring technical indicators, ML-based price prediction, walk-forward backtesting, and a comprehensive visualization suite.
- Technical Indicators -- SMA, EMA, RSI, MACD, Bollinger Bands implemented from scratch on pandas Series
- Machine Learning Models -- Random Forest and Linear Regression for price return prediction with scikit-learn
- Walk-Forward Backtesting -- Realistic expanding-window backtest engine that retrains models periodically
- Feature Engineering Pipeline -- Lagged features, rolling statistics, volatility metrics, price transforms, and target encoding
- Visualization Suite -- Publication-quality matplotlib/seaborn charts: price + indicators, RSI, MACD, correlation heatmaps, backtest diagnostics
- Sample Data Generator -- Geometric Brownian motion OHLCV generator for testing without external data sources
- Comprehensive Logging -- All steps produce structured output for easy monitoring
- Python 3.10 or higher
- pip
# Clone the repository
git clone https://github.com/yourusername/ml-finance-analyzer.git
cd ml-finance-analyzer
# Install dependencies
pip install -r requirements.txt
# (Optional) Install in development mode
pip install -e ".[dev]"Run the complete analysis pipeline on automatically generated sample data:
python examples/run_analysis.pyThis will:
- Generate 2 years of realistic OHLCV sample data for AAPL
- Compute all technical indicators
- Engineer features and train a Random Forest model
- Run a walk-forward backtest
- Generate charts and a JSON report in the
output/directory
python -m data.sample_data --tickers AAPL MSFT GOOGL --days 252 --seed 42# Run all tests with coverage
pytest tests/ -v --cov=src
# Or using the Makefile
make testml-finance-analyzer/
│
├── README.md # Project documentation
├── requirements.txt # Python dependencies
├── setup.py # Package installation config
├── Makefile # Convenience commands
├── .gitignore # Git ignore rules
│
├── data/
│ └── sample_data.py # Realistic OHLCV data generator
│
├── notebooks/
│ └── placeholder.md # Jupyter notebook directory (planned)
│
├── src/
│ ├── __init__.py # Package metadata
│ ├── data_loader.py # CSV/JSON loading + sample generation
│ ├── preprocessor.py # Cleaning, normalization, feature engineering
│ ├── indicators.py # Technical indicators (SMA, EMA, RSI, MACD, BB)
│ ├── models.py # ML models, training, prediction, backtesting
│ ├── analyzer.py # FinancialAnalyzer orchestration class
│ └── visualizer.py # Matplotlib/seaborn chart generation
│
├── tests/
│ ├── __init__.py
│ ├── test_indicators.py # Indicator calculation tests (30+ test cases)
│ └── test_models.py # Model training and backtest tests (20+ test cases)
│
└── examples/
└── run_analysis.py # End-to-end demo script
from src.data_loader import generate_sample_data
from src.indicators import compute_all_indicators, rsi
from src.models import prepare_features, train_model
from src.visualizer import plot_price_with_indicators, plot_rsi
# Generate sample data
df = generate_sample_data(days=252, ticker="AAPL")
# Compute indicators
df = compute_all_indicators(df)
# Compute RSI
df["RSI"] = rsi(df["Close"])
print(f"Latest RSI: {df['RSI'].iloc[-1]:.1f}")
# Prepare for ML
from src.preprocessor import preprocess_pipeline
processed = preprocess_pipeline(df)
X, y, scaler = prepare_features(processed)
model, metrics = train_model(X, y, model_type="rf")
# Visualize
plot_price_with_indicators(df, ticker="AAPL", save_path="output/aapl_chart.png")
plot_rsi(df, save_path="output/aapl_rsi.png")from src.analyzer import FinancialAnalyzer
# Initialize
analyzer = FinancialAnalyzer(ticker="AAPL", model_type="rf")
# Run full pipeline
analyzer.run_full_analysis(days=504)
# Or run steps individually
analyzer.load_data("sample", days=252)
analyzer.add_indicators()
analyzer.preprocess()
analyzer.train()
analyzer.run_backtest(train_split=0.8)
prediction = analyzer.predict()
analyzer.generate_plots()
analyzer.save_report()
print(analyzer.summary_report())When you run python examples/run_analysis.py, you can expect output similar to:
============================================================
ML Finance Analyzer - Full Analysis for AAPL
============================================================
Generated 504 days of sample data for AAPL
Technical indicators computed: SMA, EMA, RSI, MACD, Bollinger Bands
Preprocessed data: 435 rows, 35 columns
Model trained: RF
R2 = 0.8765
MAE = 0.0082
RMSE = 0.0124
Backtest Results:
MAE = 0.0091
RMSE = 0.0142
Direction Accuracy = 64.29%
Prediction for next day:
Expected return = 0.14%
Last close price = $182.45
Predicted price = $182.71
Charts and report saved to: output/
The output/ directory will contain:
AAPL_<timestamp>_price.png-- Price with SMA and Bollinger BandsAAPL_<timestamp>_rsi.png-- RSI with overbought/oversold linesAAPL_<timestamp>_macd.png-- MACD histogramAAPL_<timestamp>_correlation.png-- Feature correlation heatmapAAPL_<timestamp>_backtest.png-- Backtest actual vs predictedAAPL_<timestamp>_report.json-- Structured analysis report
- 100 trees, max depth 10, min samples per leaf 5
- Feature importance analysis available via
model.feature_importances_ - Good for capturing non-linear relationships in financial data
- Standard OLS regression
- Fast training, interpretable coefficients
- Best suited for data with strong linear relationships
The project includes comprehensive tests with pytest:
pytest tests/ -v --cov=src --cov-report=term-missing
- test_indicators.py: 12 tests covering SMA, EMA, RSI, MACD, Bollinger Bands, and edge cases
- test_models.py: 14 tests covering feature preparation, model training, prediction, backtesting, and edge cases
This project is licensed under the MIT License. See the LICENSE file for details.
Disclaimer: This project is for educational and research purposes only. It is not intended for real trading or investment decisions. Past performance does not guarantee future results.