A financial modeling system that combines the Heston stochastic volatility model with deep neural networks to provide enhanced stock price forecasting and volatility prediction. This project leverages LSTM networks with attention mechanisms and differential neural networks to calibrate Heston model parameters and generate accurate market predictions.
- Dual Neural Network Architecture: Separate networks for parameter calibration and volatility forecasting
- Heston Model Implementation: Advanced stochastic volatility modeling with mean reversion
- Deep Differential Networks: ML-powered parameter estimation for kappa, theta, xi, rho, and v0
- LSTM with Attention: Multi-head attention mechanism for volatility pattern recognition
- Monte Carlo Simulations: Enhanced path generation with ML-calibrated parameters
- Comprehensive Risk Analysis: VaR, CVaR, and probability-based investment insights
- Real-time Calibration: Dynamic parameter adjustment based on market conditions
- Advanced Visualizations: Multi-panel analysis with confidence intervals and distributions
- DeepDifferentialHeston Network
- Purpose: Calibrates Heston model parameters (ฮบ, ฮธ, ฮพ, ฯ, vโ)
- Architecture: Deep feedforward network with ELU activation and batch normalization
- Input: Market features and historical data
- Output: Optimized Heston parameters
- VolatilityForecastingNetwork
- Purpose: Predicts future volatility patterns
- Architecture: LSTM with multi-head attention mechanism
- Input: Sequential volatility features and market indicators
- Output: Future volatility estimates
- LSTM Layers: Capture sequential patterns in financial time series
- Multi-head Attention: Focus on relevant historical periods
- Feature Extraction: Dense layers for complex pattern recognition
- Parameter Prediction: Separate heads for price, volatility, and drift
- Clone the repository
git clone https://github.com/YavuzAkbay/Heston-Model
cd Heston-Model
- Install required packages
pip install -r requirements.txt
- For GPU acceleration (optional):
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
from heston_analysis import analyze_stock_with_heston, create_visualizations
# Analyze a stock with traditional Heston model
symbol = "AAPL"
stock_data, S_paths, v_paths, heston_model = analyze_stock_with_heston(
symbol,
forecast_months=6
)
# Create comprehensive visualizations
create_visualizations(symbol, stock_data, S_paths, v_paths, heston_model)
from enhanced_heston_ml import run_enhanced_analysis
# Run complete ML-enhanced analysis
enhanced_heston, S_paths, v_paths = run_enhanced_analysis(
symbol="TSLA",
forecast_months=12
)
from enhanced_heston_ml import EnhancedHestonML
# Initialize with custom parameters
model = EnhancedHestonML(
S0=current_price,
r=risk_free_rate,
T=time_horizon
)
# Train with custom epochs
model.train_networks(
stock_data,
epochs_param=150,
epochs_vol=300
)
# Generate forecasts
S_paths, v_paths, predicted_vol = model.enhanced_forecast(
stock_data,
forecast_months=6,
n_simulations=5000
)
- ฮบ (kappa): Mean reversion speed of volatility
- ฮธ (theta): Long-term variance level
- ฮพ (xi): Volatility of volatility (vol-of-vol)
- ฯ (rho): Correlation between price and volatility processes
- vโ: Initial variance level
- Dynamic Calibration: Parameters adjust based on market regime
- Pattern Recognition: LSTM networks identify volatility clustering
- Attention Mechanism: Focus on relevant historical periods
- Regime Detection: Automatic adaptation to market conditions
- Price Path Simulations: Monte Carlo paths with confidence intervals
- Volatility Evolution: Stochastic volatility forecasting
- Training Progress: Neural network convergence monitoring
- Return Distributions: Risk analysis with VaR calculations
- Probability of Profit: Statistical likelihood of positive returns
- Expected Returns: ML-enhanced vs traditional estimates
- Risk Metrics: VaR, CVaR, and Sharpe ratio analysis
- Volatility Forecasts: Dynamic volatility predictions
- Model Confidence: ML model reliability scores
The Heston model is governed by the following stochastic differential equations:
Price Process:
dS(t) = rS(t)dt + โv(t)S(t)dWโ(t)
Volatility Process:
dv(t) = ฮบ(ฮธ - v(t))dt + ฮพโv(t)dWโ(t)
Where dWโ(t) and dWโ(t) are correlated Brownian motions with correlation ฯ.
- GPU Acceleration: Automatic CUDA detection and utilization
- Gradient Clipping: Stable training with norm clipping
- Learning Rate Scheduling: Adaptive learning rate reduction
- Early Stopping: Patience-based training termination
- Batch Normalization: Improved convergence and stability
# DeepDifferentialHeston configuration
input_dim = 5 # Number of input features
hidden_dims = [128, 256, 128, 64] # Network architecture
dropout = 0.1 # Dropout rate
# VolatilityForecastingNetwork configuration
input_size = 10 # Sequence input size
hidden_size = 128 # LSTM hidden units
num_layers = 3 # LSTM depth
num_heads = 8
7B05
span> # Attention heads
epochs_param = 100 # Parameter network training epochs
epochs_vol = 200 # Volatility network training epochs
batch_size = 512 # Training batch size
learning_rate = 0.001 # Initial learning rate
weight_decay = 1e-5 # L2 regularization
n_simulations = 5000 # Monte Carlo paths
n_steps = 252 # Steps per year
forecast_months = 6 # Prediction horizon
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the GPL v3 - see the (https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) file for details.
This software is for educational and research purposes only. Do not use this for actual trading decisions without proper risk management and professional financial advice. Past performance does not guarantee future results. Trading stocks involves substantial risk of loss.
- Steven Heston: Original Heston stochastic volatility model (1993)
- PyTorch: Deep learning framework
- yfinance: Financial data API
- Financial Mathematics Community: Stochastic calculus foundations
Yavuz Akbay - akbay.yavuz@gmail.com
- Heston, S. L. (1993). "A Closed-Form Solution for Options with Stochastic Volatility"
- Gatheral, J. (2006). "The Volatility Surface: A Practitioner's Guide"
- Rouah, F. D. (2013). "The Heston Model and Its Extensions in Matlab and C#"
โญ๏ธ If this project helped with your financial analysis, please consider giving it a star!
Built with โค๏ธ for the intersection of mathematics, machine learning, and finance