Commit Graph

487 Commits

Author SHA1 Message Date
jgrusewski
8ce2d53d21 feat(ml): add trading_symbol field to UniverseAsset for micro contract mapping
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 14:41:22 +01:00
jgrusewski
3a60f303e3 refactor(ml): unify AssetClass — re-export from asset_selection
Remove duplicate AssetClass enum from data_pipeline module and replace
with a re-export from asset_selection, which is now the canonical
location. This ensures data_pipeline::AssetClass and
asset_selection::AssetClass are the same type, enabling direct
comparison and preventing subtle type mismatch bugs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 14:36:36 +01:00
jgrusewski
d4f4f72a50 Merge branch 'feature/operational-maturity'
# Conflicts:
#	ml/src/lib.rs
2026-02-23 14:20:23 +01:00
jgrusewski
81ae71c88e feat(ml): export data_pipeline and asset_selection types in prelude
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:40:50 +01:00
jgrusewski
1b7f72a0d2 feat(ml,trading): add gate optimizer, model registry, and P&L attribution
Gate optimizer adjusts conviction gate thresholds based on win-rate per
confidence bucket with cooldown and kill switch safety rails. Model
registry provides lifecycle management (Candidate → Staging → Production
→ Archived) with InMemoryModelRegistry for testing. P&L attribution
decomposes realized trade P&L into per-model contributions using signal
alignment.

24 new tests across 3 modules.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:39:22 +01:00
jgrusewski
1cc5a79365 feat(ml): add ActiveSetSelector for top-N asset selection by composite score
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:34:37 +01:00
jgrusewski
b94caf6d65 feat(ml): add PredictabilityScorer with rolling ML accuracy tracking
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:29:13 +01:00
jgrusewski
d2fe4c4e98 feat(ml): add asset_selection module with AssetUniverse config types
Introduces the asset_selection module with AssetClass enum (Equity/ETF/Future),
UniverseAsset struct, and AssetUniverse with filtering, lookup, and a us_starter()
preset of 7 highly liquid US assets. Includes scorer/selector placeholder stubs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:23:42 +01:00
jgrusewski
d623fb100c feat(ensemble): add autonomous weight optimizer with EMA Sharpe and safety rails
Adjusts model weights based on rolling Sharpe ratios with:
- EMA smoothing (alpha=0.1)
- Bounds: [0.05, 0.40] per model
- Max step: 0.03 per cycle
- 24h cooldown, 7-day grace period for new models
- Kill switch freeze/unfreeze
8 tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:18:53 +01:00
jgrusewski
766e16e724 feat(ml): add PreparedDataset with batch iterators for training
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:17:54 +01:00
jgrusewski
1b43d80db7 feat(ml): add DatasetManager for orchestrating data preparation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:12:33 +01:00
jgrusewski
aa67929ebc feat(ml): add cache manifest for tracking downloaded training data
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:05:52 +01:00
jgrusewski
ce8fd2b97e feat(ensemble): wire conviction gates into EnsembleCoordinator::predict()
Adds optional ConvictionGateEvaluator field to EnsembleCoordinator.
When configured, predict() evaluates all 7 gates before returning.
If any gate rejects, returns HOLD with rejection metadata.
Includes quorum ratio, trading session, and regime volatility helpers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:03:26 +01:00
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
948b2d8992 feat(ensemble): add 7-gate conviction system with evaluator and 15 tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 12:41:55 +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
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
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
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
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
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
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
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
b29817075e feat(ml): add UnifiedTrainable adapter for TGGN
Implements TGGNTrainableAdapter wrapping a candle-based projection
network (input→hidden→ReLU→output) with full UnifiedTrainable interface
including checkpoint save/load, validation, and gradient tracking.

11 tests covering forward, backward, optimizer step, checkpoint
roundtrip, validation, learning rate, and metrics collection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:48:57 +01:00
jgrusewski
bb116bad89 fix(trading_service): safetensors DQN loading, prediction shutdown, emergency order query
- Add load_from_safetensors() to DQNAgent for weight loading via VarMap
- Update RealDQNModel::from_checkpoint to try safetensors first, fall back to JSON
- Replace std::mem::forget(prediction_shutdown_tx) with proper Vec-based storage
  that sends shutdown signal and drops senders during graceful shutdown
- Wire order_manager.get_open_orders() into emergency_stop response so callers
  see which orders were active when the kill switch engaged

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:26:13 +01:00
jgrusewski
952a09a89d Merge branch 'worktree-liquid-cfc-v2' 2026-02-23 00:18:55 +01:00
jgrusewski
888daa1ced feat(liquid): add CandleCfCTrainer, re-exports, integration tests, CUDA fix
- Add CandleCfCTrainer to training.rs with Candle-based gradient training
- Update mod.rs with full CfC v2 re-exports (CandleCfCNetwork, CfCCell, etc.)
- Fix CUDA variance bug (undefined variable) and kernel compilation stub
- Add 3 integration tests: full training loop, checkpoint roundtrip, validation
- 3 new unit tests for CandleCfCTrainer (creation, single epoch, loss decrease)

73 liquid tests pass, 0 errors, 0 clippy warnings in liquid module.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:08:56 +01:00
jgrusewski
20c09d8a54 refactor(ml): delete legacy SimpleNeuralNetwork and TrainingPipeline dead code
Remove 520 lines of ndarray-based placeholder code that never performed real
gradient descent. Production training uses Candle-based trainers in ml::trainers/.

Deleted: SimpleNeuralNetwork, TrainingPipeline, NetworkConfig, ActivationType,
TrainingMetrics, NetworkInterface, MockNetwork, and 9 associated tests.
Kept: DeviceCapabilities, TrainingConfig, sub-module re-exports.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:07:59 +01:00
jgrusewski
200deaafe2 fix(ml): delete mock data loader from train_tft binary
Replace load_and_split_data() mock that generated 2000 synthetic samples
with an error-returning stub directing users to ml_training_service.

The binary retains its real infrastructure (TFTTrainer, CLI, checkpoint
storage, progress callbacks) — only the fake data generation is removed.

-120 lines of mock data, +16 lines error stub with documentation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:03:12 +01:00