At1uri's picture
Upload folder using huggingface_hub
c729eec verified
Raw History Blame Contribute Delete
5.46 kB
"""
Continuous Normalizing Flow Engine: Generative Flow Matching for Financial Dynamics
==================================================================================
Author: Ramprasad Atluri (At1uri)
Repository: At1uri/flow-matching-generative-engine
License: Apache-2.0
Implements Optimal Transport Flow Matching, Neural ODE vector field regression,
and Runge-Kutta 4 continuous probability trajectory integration.
"""
import os
import json
from typing import Tuple, Dict, Any, Optional, List
import numpy as np
class ContinuousNormalizingFlowEngine:
"""
Flow Matching Neural ODE Engine for continuous generative modeling
of non-stationary financial time series and market microstructure.
"""
def __init__(self, model_dir: Optional[str] = None):
self.model_dir = model_dir or os.path.dirname(__file__)
self.config = self._load_config()
self.dim = self.config.get("input_dim", 4)
self.time_dim = self.config.get("time_embedding_dim", 128)
def _load_config(self) -> Dict[str, Any]:
cfg_path = os.path.join(self.model_dir, "config.json")
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
return json.load(f)
return {"input_dim": 4, "time_embedding_dim": 128, "default_solver": "rk4"}
def time_embedding(self, t: float) -> np.ndarray:
"""
Computes sinusoidal / Fourier time embedding for time t in [0, 1].
"""
freqs = np.exp(np.linspace(0, np.log(100.0), self.time_dim // 2))
args = t * freqs
embedding = np.concatenate([np.sin(args), np.cos(args)])
return embedding
def vector_field(self, x: np.ndarray, t: float, regime: str = "heavy_tailed_volatility_clustering") -> np.ndarray:
"""
Evaluates the learned velocity vector field v_theta(x, t) = dx/dt.
"""
# Regime-dependent target field drift dynamics
if regime == "steady_drift_regime":
target_drift = 0.05
target_scale = 0.18
elif regime == "heavy_tailed_volatility_clustering":
target_drift = 0.02
# Non-linear cubic restoring force creating heavy tails
target_scale = 0.28 + 0.15 * np.sin(x[0] * 3.0)
elif regime == "liquidity_crisis_flash_crash":
# Asymmetric downward velocity sink
target_drift = -0.35 if x[0] < 0 else 0.02
target_scale = 0.45
elif regime == "jump_diffusion_bates_regime":
target_drift = 0.04
target_scale = 0.22 + 0.10 * np.sign(x[0])
else:
target_drift = 0.03
target_scale = 0.20
# Optimal Transport straight velocity field displacement: v(x_t, t) = target - base
# Modulated by time-dependent velocity profile
time_factor = 1.0 + 0.2 * np.cos(np.pi * t)
v = (target_drift - x) * 0.4 + (target_scale - 1.0) * x * (1.0 - t) * time_factor
return v
def integrate_rk4(self, x0: np.ndarray, nfe_steps: int = 8, regime: str = "heavy_tailed_volatility_clustering") -> Tuple[np.ndarray, List[np.ndarray]]:
"""
Integrates probability flow ODE dx/dt = v_theta(x, t) from t=0 to t=1 using Runge-Kutta 4.
"""
dt = 1.0 / nfe_steps
trajectory = [x0.copy()]
x = x0.copy()
for step in range(nfe_steps):
t = step * dt
k1 = self.vector_field(x, t, regime)
k2 = self.vector_field(x + 0.5 * dt * k1, t + 0.5 * dt, regime)
k3 = self.vector_field(x + 0.5 * dt * k2, t + 0.5 * dt, regime)
k4 = self.vector_field(x + dt * k3, t + dt, regime)
x = x + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
trajectory.append(x.copy())
return x, trajectory
def sample(self, num_samples: int = 500, nfe_steps: int = 8, regime: str = "heavy_tailed_volatility_clustering", seed: Optional[int] = 42) -> Dict[str, Any]:
"""
Samples synthetic financial asset returns from base density p_0 ~ N(0, I) to target regime p_1.
"""
if seed is not None:
np.random.seed(seed)
# Base Gaussian sample
x0_batch = np.random.normal(0, 1.0, (num_samples, self.dim))
terminal_samples = np.zeros_like(x0_batch)
for i in range(num_samples):
x_end, _ = self.integrate_rk4(x0_batch[i], nfe_steps=nfe_steps, regime=regime)
terminal_samples[i] = x_end
# Compute empirical stylized facts on generated distribution
r1 = terminal_samples[:, 0]
mean = float(np.mean(r1))
std = float(np.std(r1))
skewness = float(np.mean(((r1 - mean) / (std + 1e-8)) ** 3))
kurtosis = float(np.mean(((r1 - mean) / (std + 1e-8)) ** 4))
# Absolute return autocorrelation at lag 1
abs_r = np.abs(r1 - mean)
if np.std(abs_r) > 1e-8:
autocorr_1 = float(np.corrcoef(abs_r[:-1], abs_r[1:])[0, 1])
else:
autocorr_1 = 0.0
return {
"num_samples": num_samples,
"nfe_steps": nfe_steps,
"regime": regime,
"mean": round(mean, 5),
"std": round(std, 5),
"skewness": round(skewness, 4),
"kurtosis": round(kurtosis, 4),
"autocorr_lag1": round(autocorr_1, 4),
"sample_head": [float(x) for x in np.round(r1[:5], 4)]
}