Commit Graph

856 Commits

Author SHA1 Message Date
jgrusewski
5bc56eb9c8 feat(ml): add data_pipeline module with DatasetSpec and DatasetMode types
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:54:36 +01:00
jgrusewski
9f499282ac docs: add data pipeline & asset selection implementation plan
8-task plan across 3 phases: data pipeline (types, cache, manager,
prepared dataset), asset selection (universe, scorer, selector),
and integration wiring. 7 new files, ~51 tests estimated.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:36:45 +01:00
jgrusewski
df251a9d7e docs: add data pipeline and asset selection design
Covers automated data downloading/caching for ML training and
a tiered asset selection funnel (universe → predictability → regime → signal).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:28:02 +01:00
jgrusewski
f0bafdf30b docs: add operational maturity implementation plan (12 tasks, 6 phases)
Three pillars: 7-gate conviction system, autonomous feedback loop
with kill switch, Rust-native model registry. QuestDB analytics layer.
~55 tests, 7 new files planned across ml/ and trading_service/.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:11:28 +01:00
jgrusewski
abf4baf30e docs: add operational maturity system design (3 pillars)
7-gate conviction system, autonomous feedback loop with kill switch,
and Rust-native model registry — backed by PostgreSQL + QuestDB.
Resolve merge conflicts in hyperopt/adapters/mod.rs and enhanced_ml.rs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:02:52 +01:00
jgrusewski
4ab6975c38 fix(ml): wire activation_multiplier, cache GPU detection, fix stale comments
- Scale model_memory_mb by activation_multiplier in resolve_batch_size()
  so TFT (2.5x) gets proportionally smaller batches than DQN (1.0x)
- Add cached_capabilities() with OnceLock to avoid spawning nvidia-smi
  on every call to CampaignConfig::dqn_default/ppo_default/PpoTrainer::new
- Add PartialEq to GpuCapabilities and simplify serde roundtrip test
- Update stale "RTX 3050 Ti" and "Exceeds GPU limit (230)" comments
  to reflect dynamic detection
- Document Auto variant silent CPU fallback behavior (no callers affected)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:49:22 +01:00
jgrusewski
fd2221e50e feat(ml): export GPU types in prelude
Add DeviceConfig and GpuCapabilities re-exports to ml::prelude so
downstream crates can import GPU management types via a single
`use ml::prelude::*` statement.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:41:10 +01:00
jgrusewski
6425eb150b feat(ml): use dynamic GPU detection for hyperopt campaign batch sizes
Replace hardcoded max_batch_size: 230 in CampaignConfig::dqn_default()
and ppo_default() with dynamic GPU detection via GpuCapabilities::detect()
and resolve_batch_size(). Update test to no longer assert <= 230.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:40:27 +01:00
jgrusewski
0409ad38a0 feat(ml): replace hardcoded batch_size 230 with dynamic GPU detection in PPO trainer
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:35:26 +01:00
jgrusewski
c0751eb61b refactor(ml): use DeviceConfig::Auto in ensemble adapters
Replace Device::cuda_if_available(0).unwrap_or(Device::Cpu) with
DeviceConfig::Auto.resolve().unwrap_or(Device::Cpu) in DQN, PPO, TFT,
and Mamba2 ensemble inference adapters so device selection goes through
the centralized GPU detection module.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:30:17 +01:00
jgrusewski
aac8142284 feat(ml): NaN gradient detection with auto-halt during training
Add check_gradients_finite() to gradient_utils.rs that detects NaN/Inf
in GradStore before optimizer step. Uses efficient sum_all approach
where any NaN element produces a NaN sum. Includes 3 unit tests
(finite pass, NaN detected, empty vars pass).

DQN and PPO training loops already wired via gradient_accumulation
module's check_gradients_finite (all 6 paths: standard policy/value,
remainder policy/value, LSTM policy/value).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:30:01 +01:00
jgrusewski
6ffa38cc04 feat(ml): NaN gradient detection with auto-halt during training
Add check_gradients_finite() utility that scans GradStore for NaN/Inf
values. Wire into DQN (after gradient accumulation, before optimizer step)
and PPO (both MLP and LSTM training paths, after backward pass).

Prevents silent model corruption from exploding gradients or numerical
instability — training halts immediately with a descriptive error.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:26:49 +01:00
jgrusewski
d25f076f2a refactor(ml): use canonical DeviceConfig from gpu module in Liquid CfC
Replace local DeviceConfig enum definition in liquid/candle_cfc.rs with
a re-export from the central crate::gpu::DeviceConfig, eliminating
duplication while preserving all existing API and tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:25:31 +01:00
jgrusewski
10f9cfadb7 feat(infra): GPU training launcher with local/cloud routing
Add train_launcher.sh that detects local GPU VRAM and routes training
to local or Scaleway cloud. Auto-selects batch size per model based on
available VRAM tier. Maps model names to actual ml/examples/train_*.rs
cargo targets. Document Scaleway GPU instance types, setup procedure,
batch size tables, and cost estimates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:19:58 +01:00
jgrusewski
12642d371a feat(ml): add GpuCapabilities for hardware detection
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:15:52 +01:00
jgrusewski
985b0f73d6 feat(ml): add gpu module with DeviceConfig enum
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:11:20 +01:00
jgrusewski
17727d5db9 docs: add dynamic GPU detection implementation plan
8 bite-sized tasks with TDD approach, exact file paths, and complete code.
Covers: DeviceConfig relocation, GpuCapabilities detection,
ModelMemoryEstimate per-model profiles, and wiring into PPO trainer
and hyperopt campaign.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:56:45 +01:00
jgrusewski
ea81c751c0 docs: add dynamic GPU detection design plan
Centralizes GPU device selection, capability detection, and per-model
batch size optimization to replace hardcoded RTX 3050 Ti limits.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:53:04 +01:00
jgrusewski
b5fec19971 test(trading_service): enhanced ML service component tests
Add 16 unit tests for Enhanced ML service components:
- EnsembleConfig::default() values (min_models, thresholds, voting)
- FeaturePreprocessor::classify_feature_type() for price, volume,
  technical, sentiment, and unknown features
- FeaturePreprocessor normalization (z-score, tanh fallback, zero std_dev)
- FeaturePreprocessor default stats validation
- RuntimeModelInfo creation for all 5 model types (DQN/PPO/TFT/Mamba/LNN)
- ModelPerformanceMetrics::default() zero initialization
- FeatureNormStats volatility default bounds

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:50:43 +01:00
jgrusewski
2bce9859cc test(trading_service): unit tests for risk service VaR and risk limits
Add 25 unit tests for the RiskServiceImpl pure functions:
- Parametric VaR fallback formula (notional * 0.02)
- Equal contribution percentage for N symbols (including empty)
- Drawdown computation (empty, positive PnL, negative, mixed)
- Returns from executions (empty, single, sorted, zero-price filtering)
- Volatility (empty, single, constant, known series)
- Sharpe ratio (insufficient data, zero vol, positive returns)
- Sortino ratio (insufficient data, no downside, mixed)
- VaR square-root-of-time scaling (1d→5d→30d)
- Concentration risk level thresholds
- Risk constants validation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:49:50 +01:00
jgrusewski
dcc6661fa8 feat(ml): ensemble-level hyperopt with joint model weight optimization
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:38:49 +01:00
jgrusewski
18e00fff12 feat(trading_agent): correlation matrix support in Markowitz allocation
Add optional correlation matrix parameter to mean-variance optimization.
When provided, builds full covariance matrix (Sigma[i][j] = corr[i][j] *
vol_i * vol_j) instead of diagonal-only. Existing API unchanged — callers
pass None by default. New allocate_with_correlations() public method for
correlated optimization. Five new tests: identity-matches-diagonal,
correlated-differs-from-diagonal, invalid dimensions, non-square matrix,
and non-MeanVariance delegation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:33:14 +01:00
jgrusewski
940aae71b1 fix(trading_service): NaN/Inf guards in feature normalization
Add defensive checks to FeaturePreprocessor::normalize():
- Return 0.0 with warning log for NaN/Inf input values
- Clamp z-score output to [-10, 10] to prevent extreme values
- Add 4 unit tests covering NaN, Inf, -Inf, and extreme value clamping

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:24:07 +01:00
jgrusewski
10032ca13f feat(ml): SHA-256 checksum validation for model checkpoint integrity
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:23:51 +01:00
jgrusewski
15c0fb5397 merge: pull liquid CfC v2 and codebase deduplication from main into production-hardening 2026-02-23 10:09:25 +01:00
jgrusewski
2e4b0c9455 fix(ml): per-model circuit breakers in ensemble — filter NaN/Inf, clamp confidence
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:06:53 +01:00
jgrusewski
5a2c92484c docs(risk): document Redis monitoring deferral for kill switch
Replace the TODO for spawning a background Redis health-check task
with an architectural decision comment. Local AtomicBool provides
immediate process-level protection; Redis monitoring is deferred to
multi-service deployment with a clear implementation roadmap.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:06:42 +01:00
jgrusewski
e36698ef14 fix(ml): GPU OOM detection with automatic CPU fallback in inference engine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:06:40 +01:00
jgrusewski
3637b49218 fix(trading_service): wire real portfolio notional into VaR calculations
Move position fetching before VaR calculation in both get_va_r and
get_risk_metrics so the portfolio notional is computed from real
position data (sum of |quantity * avg_price|) instead of the fake
confidence_level * 1_000_000.0 placeholder. Falls back to 100_000.0
when the portfolio is empty.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:04:34 +01:00
jgrusewski
51378aa4cc fix(trading_agent): wire real position data into allocation calculations
Replaces hardcoded zeros in AssetAllocation with real position data
queried from agent_orders. Adds fetch_current_positions() helper that
derives net quantity per symbol (buy - sell) and reuses it in both
allocate_portfolio and rebalance_portfolio to eliminate SQL duplication.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:54:12 +01:00
jgrusewski
cc623af5fa fix(ml): replace std::process::exit with Result propagation in temporal_guard tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:46:05 +01:00
jgrusewski
7fd5ad4286 docs: production hardening phase 2 implementation plan — 19 tasks
4 layers: Safety Net (6 tasks), Correctness (6 tasks incl. CfC ensemble),
Verification (4 tasks), Training Infrastructure (3 tasks incl. Databento).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:39:13 +01:00
jgrusewski
fad71033ff docs: production hardening phase 2 design — $100K live trading readiness
4-layer risk-prioritized approach: safety net (crash prevention),
correctness (accurate calculations + liquid CfC ensemble integration),
verification (test coverage), training infrastructure (Databento + GPU).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:33:55 +01:00
jgrusewski
b88fd62af2 feat(ml): add Diffusion model (DDPM/DDIM) for price path generation
- NoiseScheduler: precomputed cosine/linear alpha_bar schedules
- Denoiser: FC network with sinusoidal time embedding + SiLU + residual
- DDIMSampler: deterministic fast sampling (10 steps from 1000 timesteps)
- DiffusionTrainableAdapter: UnifiedTrainable for unified training pipeline
- Hyperopt adapter with ParameterSpace (9 params, batch ≤64 for 4GB GPU)
- ModelType::Diffusion registered in common + coordinator
- 41 tests passing (config=3, noise=7, denoiser=4, sampler=5, trainable=12, hyperopt=7)
- OOM-safe: FC denoiser instead of U-Net, small hidden dims, conservative defaults

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:32:44 +01:00
jgrusewski
83054548b8 feat(ml): add xLSTM architecture (sLSTM + mLSTM blocks, network, trainable, hyperopt)
- sLSTM: exponential gating for long-range memory retention
- mLSTM: matrix memory with multi-head attention for higher capacity
- XLSTMBlock: pre-LayerNorm + residual connections
- XLSTMNetwork: stacked blocks with configurable sLSTM/mLSTM ratio
- UnifiedTrainable adapter for unified training pipeline
- Hyperopt adapter with ParameterSpace (9 params)
- ModelType::XLSTM registered in common + coordinator
- 45 tests passing (38 architecture + 7 hyperopt)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:13:35 +01:00
jgrusewski
a51fe0d30d Merge feat/production-hardening: resolve 53 TODOs across 5 phases
Phase 1: ML pipeline verification (checkpoint roundtrip tests, feature pipeline tests, DQN VarMap bug fix, deleted 585 lines dead code)
Phase 2: Service production logic (real portfolio metrics, VaR positions, proto population, safetensors loading, shutdown handling)
Phase 3: Backtesting & data (equity curve, DBN metadata, progress callbacks, cross-symbol validation, event filtering)
Phase 4: ML crate TODOs (statrs t-distribution, quantization savings, safetensors header, microstructure features, 45-action masking, confidence EMA, AttentionMask)
Phase 5: Infrastructure/cleanup (TLS/OCSP docs, compliance roadmap, metrics docs, regime features, execution roadmap, auth #[ignore], chaos docs)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:04:43 +01:00
jgrusewski
4eacd4e22f feat(ml): add KAN architecture + TLOB/KAN trainable/hyperopt adapters
Phase 2-3 of ensemble expansion:
- KAN (Kolmogorov-Arnold Network): B-spline basis, layer, network, trainable adapter
- TLOB UnifiedTrainable adapter with 3D input support (batch, seq, features)
- Hyperopt adapters for both KAN and TLOB (ParameterSpace + metrics)
- ModelType::KAN variant registered in common, coordinator, lib.rs
- 44 new tests, all passing, zero warnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:32:25 +01:00
jgrusewski
d777d714b2 feat(liquid): wire Liquid CfC into trading service and gRPC trainer
Closes the integration gap between Liquid CfC and DQN/PPO by adding:
- LiquidTrainer with gRPC progress callbacks, early stopping, and
  checkpoint management (ml/src/trainers/liquid.rs)
- LiquidModel wrapper in enhanced_ml.rs for hot-loading from safetensors
- Ensemble weight rebalance: DQN 0.25, PPO 0.25, TFT 0.20, Mamba2 0.15,
  Liquid-CfC 0.15

Verified: 81 liquid unit tests + 3 integration tests + 211 trading_service
tests pass, 0 compile errors across workspace.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:14:33 +01:00
jgrusewski
4db5b86d9b chore(tests): clean stale FIXME in test_runner, document lock contention tracking
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:14:24 +01:00
jgrusewski
3544e800f8 fix(services): regime feature extraction, correlation docs, execution roadmap, auth #[ignore], chaos docs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:14:14 +01:00
jgrusewski
2980e6c50a docs(services): TLS/OCSP delegation, compliance roadmap, metrics doc comments
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:14:05 +01:00
jgrusewski
0e3144813a feat(ml): add hyperopt adapter for TGGN (ParameterSpace + metrics)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:08:00 +01:00
jgrusewski
d4a0255595 feat(ml): AttentionMask causal masking, document multi-asset DQN and conversion layer
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:03:53 +01:00
jgrusewski
cfadd7d3dc feat(ml): factored 45-action masking, confidence EMA, RAII memory docs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:03:44 +01:00
jgrusewski
4e228f127f feat(ml): implement microstructure features, TFT resource monitoring, document disabled tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:03:35 +01:00
jgrusewski
9e7a4bf086 fix(ml): replace hardcoded t-distribution with statrs, compute quantization savings, parse safetensors header
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:03:26 +01:00
jgrusewski
de8b58ae06 Merge branch 'feat/tggn-fullstack' — TGGN UnifiedTrainable adapter
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 01:01:03 +01:00
jgrusewski
60593ba8bb fix(services): wire event filter, document job store, implement cross-symbol validation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:50:07 +01:00
jgrusewski
c45e4a039a feat(backtesting): DBN file metadata caching and progress callback for strategy engine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:49:47 +01:00
jgrusewski
1896bb5a38 fix(backtesting): wire equity curve and drawdown periods to GetBacktestResults
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:49:17 +01:00