Hybrid_Pricing_Engine
⚙️ QUNEX: Hybrid Pricing Engine & Parameter Optimization Blueprint
The QUNEX engine serves as the high-fidelity pricing simulation layer for our Paper Trading Platform. Its primary job is to ingest true hourly market benchmarks from live assets and generate synthetic, minute-by-minute price tracks in between. Because every stock ticker possesses unique volatility, momentum behavior, and tracking characteristics, a one-size-fits-all formula will fail. The system uses a dedicated Machine Learning Parameter Optimizer Pipeline to study historical market shapes and mathematically map custom configuration rules tailored to individual stock behaviors.
🏛️ Mathematical Framework & Code Mapping
Our minute-by-minute simulated price updates follow a continuous composite path driven by three structural market forces: $\(y_{\text{new}} = y_{\text{current}} + \alpha + \beta + \gamma\)$ The following matrix shows how our abstract mathematical forces map directly onto real-world code behaviors and variable definitions:
| Variable | Core Component | Financial Metric Mapping | System Role / Behavioral Intent | Code Function Mapping |
|---|---|---|---|---|
| α₀ | Random Trigger | Average True Range (ATR) | Generates baseline market bid-ask jitter and micro-noise. | alpha0 factor inside get_alpha() |
| β₀ | Trend Accelerator | Historical Streak Mean | Compounds buying/selling pressure trends (Hope & Panic). | beta0 velocity scale inside get_beta() |
| γ₀ | Gravity Brake | Standard Deviation (σ) | Enforces mean reversion toward the real hourly market anchor. | yamma0 multiplier inside get_yamma() |
📈 Engine Component Rules Explained Simply## 1. Alpha (α) — Random Trigger
This module creates minor minute-by-minute structural price friction. It keeps the asset dynamic even when no overarching trends are acting on it.
- In Code Validation: The function get_alpha() polls a uniform random generator bounded between 0.00 and 1.00, multiplies it by the asset's custom alpha0 setting, and clamps the result to a strict two-decimal float precision format.
- Direction Indicator: A uniform choice check flips a virtual coin to pick 1 or -1. This step removes tracking bias, letting the asset float naturally sideways in the absence of market pressure.
2. Beta (β) — Trend Accelerator
This module models structural herd behavior (market momentum). Instead of treating micro-movements as independent events, it tracks consecutive price directions to simulate short-term cascading trends.
- In Code Validation: The function get_momentum() tracks direction memory. If a new movement matches the previous minute's trend direction, the persistence counter increments. If the direction flips, the historical streak memory is broken and resets instantly to its base coordinate velocity (1 or -1).
- Velocity Multiplier: The functional function get_beta() multiplies the running streak sequence length by beta0, mathematically compounding buying or selling surges.
3. Gamma (γ) — Gravity Brake
This acts as a dynamic rubber band snapping our simulated asset price back toward the underlying real-world market target.
- In Code Validation: The function get_yamma() measures the absolute percentage distance between our current high-frequency tracking line and the target hourly benchmark.
- Proportional Pull Force: The further away our simulation drifts from the true market line, the wider the percentage deviation expands. This causes yamma to inject a stronger, directional correction pull.
🎯 System State Engine Statuses
The environment restricts pricing behaviors using a strict binary state machine handled inside get_status(). Transitions switch boundaries automatically based on the relative location of our high-frequency line against the hourly benchmark vector.
[ High-Frequency Price (y_current) approaches Hourly Target Anchor ]
│
▼
Has Target Anchor been crossed?
├── NO ──► [ Status: Chasing ] ──► Gamma Attraction is ON
└── YES ──► [ Status: No-Chasing ] ──► Gamma Snap resets to 0
1. Status: Chasing (status = True)
- Condition: The high-frequency tracking price line has not yet matched, intersected, or crossed the targeted hourly benchmark level from its initial boundary orientation.
- Engine Behavior: The Gravity Brake (γ) is ON. The engine measures asset tracking deviation and applies a strong mean-reversion force pulling the price toward the target benchmark.
2. Status: No-Chasing (status = False)
- Condition: The high-frequency simulation price path successfully crosses or equals the active \(y_{\text{anchor}}\) coordinate level.
- Engine Behavior: The Gravity Brake is turned completely OFF (γ = 0). The asset is freed from the anchor's gravity pull, allowing raw momentum (β) and random noise (α) to dictate movements until a new hourly anchor update arrives.
🧠 Neural Network Parameter Optimizer
Because the paper trading platform hosts many different types of stock tickers (e.g., tech, utilities, small-cap), using static settings will break realism. High-volatility tickers will overshoot boundaries, while stable assets will track sluggishly. To solve this, a machine learning automation pipeline decouples from live execution, extracting custom setting triplets (α₀, β₀, γ₀) for any specific stock by running 4 sequential optimization stages:
[1. Data Extraction] ──► Collects raw historical 1-minute blocks & isolates hourly milestones. │ ▼ [2. Feature Generation] ──► Runs massive stochastic trials & converts absolute prices to scale-free inputs. │ ▼ [3. CNN Optimization] ──► Trains a 1D-CNN temporal network to match price shapes to parameters. │ ▼ [4. Platform Ingestion] ──► Passes real asset data to the model and saves a custom JSON config.
1. High-Density Intraday Data Extraction (raw_data.py)
Our optimization pipeline begins by downloading historical datasets via the Yahoo Finance API (yfinance). To bypass scraping protection and avoid throttling, it spoofs user-agent browser variables over dedicated session objects.
- Time Windows: It loops backward day-by-day to extract deep 1-minute intraday intervals strictly between 09:25 AM and 15:25 PM.
- Anchor Filtering: It isolates true market milestones at exactly 25 minutes past each hour (yielding exactly 7 anchor points per trading day). Incomplete sessions, market half-days, or holiday frames are validated and dropped.
2. Scale-Free Feature Data Generator (data_generator.py)
Neural networks fail when evaluating absolute raw dollar prices due to scale differences across assets (e.g., a $10 stock vs. a $4,000 stock). This module prepares scale-independent inputs:
- Feature Vector 1 (Log Returns): Converts the absolute price path into relative minute-by-minute changes: \(\log(P_t) - \log(P_{t-1})\).
- Feature Vector 2 (Anchor Proximity): Calculates the normalized distance to the active target level: \((P_{\text{current}} - P_{\text{anchor}}) / P_{\text{anchor}}\).
- Mass Matrix Sampling: The generator runs tens of thousands of engine simulation trials, assigning random parameter ranges across historical day tracks to compile large multi-dimensional tracking matrices (\(X_{\text{train}}, Y_{\text{labels}}\)) exported as binary numpy files.
3. 1D-CNN Temporal Machine Learning Architecture (train_model.py)
The pipeline runs a custom One-Dimensional Convolutional Neural Network (1D-CNN) engineered specifically to detect temporal patterns, trend shifts, and mean-reversion speeds across sequence blocks.
- Convolution Blocks: The network maps mathematical trends over time across structural timeline blocks, progressively downsizing dimensions using Max Pooling and Adaptive Average Pooling arrays.
- Dense Regulation Layers: Linear hidden maps project learned feature matrices onto continuous multi-label nodes. A Dropout(0.2) block is integrated to restrict the model from over-fitting or relying on synthetic simulation noise.
- Convergence Training: The system allocates an 80/20 train/validation data split, updates network weights using Mean Squared Error (MSE) loss metrics over an Adam optimization suite, and saves the final serialized model parameters to disk.
4. Production Inference & Platform Config Export (helper.py & Parameter_optimiser.py)
The orchestrator acts as the production deployment manager. It loads the compiled neural network weights and runs a forward pass over a stock ticker's actual historical market data.
- Parameter Extrapolations: The model analyzes how the real stock behaves relative to its anchors, averages the daily outputs, and extracts the optimal parameter triplet (α₀, β₀, γ₀) unique to that asset.
- System Integration: The script compiles verification plots and outputs a clean JSON parameter card containing structural metric configurations. This card is written directly to the paper trading deployment folder, allowing the simulation engine to read and mimic that exact stock's trading personality instantly at runtime.
🛠️ Network Hyperparameters & Blueprint Settings
The machine learning framework utilizes specialized operational boundaries to control how the parameters are extracted from the synthetic historical runs:
- Optimizer Engine: Adam (learning_rate = 0.001) to handle multi-label continuous target convergence cleanly.
- Loss Function Metric: Mean Squared Error (nn.MSELoss()) calculating simultaneous Euclidean distance error arrays across all three parameters (α₀, β₀, γ₀).
- Batch Slicing Configuration: 64 samples per tensor block batch array allocation.
- Data Split Weights Matrix: 80% assigned to model feature training, 20% reserved for validation cross-checking.
- Regularization Constraints: Dropout(p=0.2) applied directly to the primary dense hidden layer block to restrict network over-reliance on artificial matrix trends.
📋 Production Deployment JSON Structure
Once the optimized configuration is saved, the live trading application parses it to adapt simulation behaviors instantly. Below is a blueprint example of a generated tracking card (INFY.NS_engine_config.json):
{ "ticker": "INFY.NS", "parameters": { "alpha0": 1.140826, "beta0": 0.082419, "gamma0": 0.231574 }, "last_updated": "2026-08-18 12:54:11" }
- ticker: The targeted financial identifier scanned by the framework.
- alpha0: Volatility drift scaling parameter matching historical True Range bounds.
- beta0: Compound momentum growth scaling constraint assigned to sequential step matching.
- gamma0: Gravity reversion coefficient controlling attraction speed back to the anchor line.
- last_updated: Explicit execution timeline stamp validating the training block freshness index.
📂 Production Storage Blueprint
The system pipeline automatically orchestrates files and tracks system health using a standardized workspace tree:
- QuNex/NN_pipeline/Price_maker/data_cache/
- Contains parsed market files (real_1m_data.csv, real_anchors.csv).
- Stores compact training feature tensors (X_train_features.npy, Y_train_labels.npy).
- Serializes active neural network weights (parameter_estimator_model.pth).
- QuNex/NN_pipeline/Price_maker/images/
- Generates convergence graphs (nn_convergence_metrics.png).
- Saves monthly simulation overlay maps (full_month_simulation_accuracy.png).
- QuNex/NN_pipeline/Price_maker/config/
- Deploys the automated, live configuration cards ([TICKER]_engine_config.json).