The Neural-Driven Quant Finance Engine is an institutional-grade, Event-Driven Backtesting system designed for rigorous financial research and trading simulation. It leverages State-of-the-Art (SOTA) Deep Learning architectures to detect market regimes and forecast asset returns with high fidelity.
At its core, the system integrates iTransformer (Inverted Transformer) for multivariate time-series forecasting and InvAD (Inversion Anomaly Detection) for robust crisis avoidance. Portfolio allocation is handled by NeuralHRP, a novel adaptation of Hierarchical Risk Parity that uses attention-derived market topology to cluster assets. This engine is built to simulate real-world trading conditions, including T+1 execution delays, liquidity constraints, and realistic fee structures.
- Risk Shield:
- InvAD (Inversion Anomaly Detection): A specialized Denoising Autoencoder that monitors market stability. It treats "Normal" market conditions as the manifold and detects "Crisis" states by measuring the reconstruction error (Panic Score), effectively shielding the portfolio from drawdowns.
- Signal Engine:
- iTransformer: A multivariate forecasting model that inverts the standard Transformer architecture. It embeds the entire time series of each asset as a single token, applying self-attention across the asset dimension to capture complex, dynamic correlations.
- Allocation:
- NeuralHRP: An advanced risk management technique that performs Hierarchical Risk Parity using the "Symmetrized Attention Matrix" from the iTransformer as the distance metric, ensuring that assets with similar structural risks are clustered together.
- Feature Engineering:
- Utilizes advanced financial features including Fractional Differentiation (FFD) for stationarity preservation without memory loss, Path Signatures, and VPIN (Volume-Synchronized Probability of Informed Trading) for microstructure analysis.
- Execution:
- Realistic Simulation: Fully event-driven architecture that accounts for T+1 execution delays (orders generated at Close, executed at next Open).
- Cost Modeling: Incorporates IBKR's fixed and tiered fee structures, along with slippage and liquidity checks to prevent unrealistic fills.
The system follows a modular, unidirectional data flow designed for reproducibility and scale:
data_loader.py -> features.py -> models -> strategies.py -> engine.py -> reporting.py
- Data Loader (
data_loader.py): Fetches and caches historical market data (yfinance) and macroeconomic indicators (FRED), aligning them to a Master Index (SPY) to ensure data integrity. - Feature Engineering (
features.py): Transforms raw OHLCV data into stationarity-preserving features ready for neural network consumption. - Models (
src/models/):forecasting.py: Runs the iTransformer to generate return forecasts and attention maps.regime.py: Runs the InvAD model to compute the current "Panic Score."
- Strategy Controller (
strategies.py): Orchestrates the decision logic. It checks the Risk Shield first; if the market is safe, it uses the Signal Engine's forecasts and the NeuralHRP allocator to generate target portfolio weights. - Execution Engine (
engine.py): Simulates the trading environment, managing order lifecycles, cash flows, margin, and T+1 settlements. - Reporting (
reporting.py): Calculates professional performance metrics (Sharpe, Sortino, Calmar) and generates visual tearsheets.
- Python 3.10 or higher
- Git
-
Clone the Repository:
git clone https://github.com/your-username/quant-finance-engine.git cd quant-finance-engine -
Create a Virtual Environment:
python -m venv venv # Windows .\venv\Scripts\activate # Linux/Mac source venv/bin/activate
-
Install Dependencies:
pip install -r requirements.txt
The system uses a .env file for sensitive configurations. You must create this file in the project root.
-
Copy the example:
cp .env.example .env
-
Edit
.envand add your keys:# Required for Macroeconomic Data FRED_API_KEY=your_fred_api_key_here
- FRED_API_KEY: Get a free API key from FRED St. Louis Fed.
The main entry point for the backtester is main.py.
Run the standard backtest with default settings:
python main.pyYou can customize the simulation using command-line arguments:
| Argument | Description | Default |
|---|---|---|
--capital |
Initial Capital (USD) | 10,000 |
--start |
Start Date (YYYY-MM-DD) | 2006-01-01 |
--end |
End Date (YYYY-MM-DD) | Yesterday |
--leverage |
Maximum allowed leverage (e.g., 1.5 for 150%) | 1.0 |
--universe |
Asset Universe: dynamic (Era-based) or live (Current) |
live |
--optimize |
Mode: train to run hyperparam search, run to use optimized params |
None |
--target_vol |
Override target annualized volatility (e.g., 0.20) | None |
--trials |
Number of trials for optimization | 50 |
Aggressive Growth Run:
python main.py --capital 50000 --leverage 2.0 --target_vol 0.25 --universe dynamicOptimization Search:
python main.py --optimize train --trials 100quant-finance-engine/
├── main.py # Entry point
├── requirements.txt # Project dependencies
├── .env # Configuration keys
├── src/
│ ├── engine.py # Event-Driven Execution Engine
│ ├── strategies.py # Strategy Controller & Logic
│ ├── data_loader.py # Data fetching & alignment
│ ├── features.py # Feature Engineering
│ ├── algorithm.py # Base algorithm classes
│ ├── performance.py # Metric calculations
│ ├── reporting.py # Plotting & Tearsheets
│ ├── models/
│ │ ├── forecasting.py # iTransformer Implementation
│ │ └── regime.py # InvAD (Risk Shield) Implementation
│ ├── optimization/
│ │ ├── mst.py # NeuralHRP Allocator
│ │ └── hyperparameters.py # Optuna Optimization
│ └── assets/ # Images and static resources
└── results/ # Output reports and artifacts
Not Investment Advice. This software is for educational and research purposes only. The strategies and models included here are simulations and do not guarantee future results. Financial trading involves significant risk, and you should not trade with money you cannot afford to lose.
