Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ML Finance Analyzer

Python 3.10+ scikit-learn pandas License: MIT Code style: black

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.


Features

  • 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

Installation

Prerequisites

  • Python 3.10 or higher
  • pip

Setup

# 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]"

Quick Start

Run the complete analysis pipeline on automatically generated sample data:

python examples/run_analysis.py

This will:

  1. Generate 2 years of realistic OHLCV sample data for AAPL
  2. Compute all technical indicators
  3. Engineer features and train a Random Forest model
  4. Run a walk-forward backtest
  5. Generate charts and a JSON report in the output/ directory

Generate Custom Sample Data

python -m data.sample_data --tickers AAPL MSFT GOOGL --days 252 --seed 42

Run Tests

# Run all tests with coverage
pytest tests/ -v --cov=src

# Or using the Makefile
make test

Project Structure

ml-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

Usage Examples

Programmatic API

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

Using the Analyzer Class

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

Example Output

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 Bands
  • AAPL_<timestamp>_rsi.png -- RSI with overbought/oversold lines
  • AAPL_<timestamp>_macd.png -- MACD histogram
  • AAPL_<timestamp>_correlation.png -- Feature correlation heatmap
  • AAPL_<timestamp>_backtest.png -- Backtest actual vs predicted
  • AAPL_<timestamp>_report.json -- Structured analysis report

Model Details

Random Forest Regressor

  • 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

Linear Regression

  • Standard OLS regression
  • Fast training, interpretable coefficients
  • Best suited for data with strong linear relationships

Testing

The project includes comprehensive tests with pytest:

pytest tests/ -v --cov=src --cov-report=term-missing

Test Coverage

  • 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

License

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.

About

Machine Learning Financial Data Analysis Toolkit with technical indicators, predictive models, and visualization

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages