Commit Graph

4015 Commits

Author SHA1 Message Date
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
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
b7c92d60f9 fix(trading_service): use real position sizes and marginal VaR contributions
Replace hardcoded position_size: 1000.0 with actual position quantities
from fetch_positions(). Compute contribution_pct as marginal VaR ratio
(symbol_var / portfolio_var * 100) instead of naive equal-weight split.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:20:25 +01:00
jgrusewski
164e96bf44 fix(trading_agent): wire real volatility, prices, and metrics into allocate_portfolio
Replace 7 hardcoded 0.0 values with real calculations:
- target_quantity from last close price
- portfolio_volatility from log return stddev * sqrt(252)
- portfolio_sharpe from weighted returns / portfolio vol
- var_95 parametric VaR
- max_drawdown_estimate from vol approximation
- rebalance_delta as target - current (0 until positions available)
- per-asset volatility from price bars (was hardcoded 0.15)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:20:05 +01:00
jgrusewski
952a09a89d Merge branch 'worktree-liquid-cfc-v2' 2026-02-23 00:18:55 +01:00
jgrusewski
33576dddb9 fix(services): populate event protos, compute max drawdown, document integration gaps
Tasks 8-14 production hardening batch:

- Populate Order/Position/Execution proto messages from JSON payload in event
  stream converters instead of returning None (Task 9)
- Compute max_drawdown from cumulative PnL samples in A/B testing pipeline
  instead of hardcoded 0.0 (Task 11)
- Document feature pipeline integration blockers with detailed roadmap
  comments in state.rs and trading.rs (Task 8)
- Document realized PnL gap: TradingPosition lacks the field, repository
  has async method incompatible with Iterator::map (Task 10)
- Document ML order quantity gap in api_gateway proxy: MlOrderResponse
  proto lacks quantity field (Task 12)
- Document per-symbol weight tracking roadmap in ensemble_coordinator (Task 13)
- Document OHLCV bar pipeline upgrade roadmap in state.rs (Task 14)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:18:39 +01:00
jgrusewski
5a90eaba8c Merge branch 'refactor/codebase-deduplication' 2026-02-23 00:11:34 +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
62c2439fe5 test(ml): add feature extraction pipeline integration tests
4 tests validating the 51-dim feature extraction pipeline:
- DBN data loading (graceful skip if file absent)
- Synthetic bars: dimension check (51-dim), no NaN/Inf
- Value range bounds (-100 to 100)
- Streaming vs batch consistency (element-wise 1e-10 tolerance)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:08:17 +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
d9fa536511 docs: add ML ensemble expansion implementation plan (36 tasks, 6 phases)
Sequential build plan for 5 model integrations (TGGN, TLOB, KAN,
xLSTM, Diffusion) with TDD, worktree isolation, and full trait
implementations (UnifiedTrainable + ParameterSpace + hyperopt).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 00:05:28 +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
jgrusewski
1408d33f4f docs: add ML ensemble expansion design (7→10 models, 5 integrations)
Approved design for expanding the ensemble with KAN, xLSTM, and
Diffusion architectures plus bringing TGGN/TLOB to full integration.
Sequential build order, no god classes, modular decomposition.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:56:38 +01:00
jgrusewski
4dd6e24a4e fix: resolve rebase conflict markers and align ModelType semantics
Fix leftover conflict markers from rebase onto main. Align as_str()
with main's semantics (general-purpose model names), add separate
s3_prefix() for S3 storage paths, and fix to_db_string() to preserve
per-variant database values.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:56:29 +01:00
jgrusewski
edd5a503da test(ml): add TFT + Mamba2 checkpoint roundtrip integration tests
Extend checkpoint_roundtrip.rs with 4 new tests for sequence-buffered models:

- TFT adapter deterministic inference: verifies same adapter produces
  identical direction/confidence on repeated calls with stable buffer
- TFT quantile metadata: confirms quantiles are absent during buffering
  phase and present (with correct count) after buffer fills
- Mamba2 adapter deterministic inference: same pattern as TFT, verifies
  direction/confidence stability and correct model name ("MAMBA-2")
- Mamba2 CheckpointManager roundtrip: saves/loads via Checkpointable
  trait on Mamba2SSM, verifies metadata tags and hyperparameters

All 10 tests (6 existing DQN/PPO + 4 new TFT/Mamba2) pass consistently.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:55:23 +01:00
jgrusewski
7c7f718272 feat(liquid): add LiquidTrainableAdapter implementing UnifiedTrainable
Full adapter bridging CandleCfCNetwork to the unified training pipeline
with VarMap-based checkpointing, AdamW optimizer, and gradient norm
tracking. Includes 10 unit tests covering creation, training steps,
validation, metrics, learning rate, checkpoint roundtrip, and error cases.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:55:04 +01:00
jgrusewski
834f097ffe feat(liquid): add LiquidInferenceAdapter for ensemble predictions
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:45:35 +01:00
jgrusewski
4ec8e58cf4 refactor(data): replace inline CircuitBreaker with common::resilience::CircuitBreaker
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
4a14e53eeb refactor(broker_gateway): replace inline CircuitBreaker with common::resilience::CircuitBreaker
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
bb4d4159d8 refactor(ml): implement CircuitBreakerTrait for ML circuit breaker
Bridge the ML crate's parking_lot::RwLock-based CircuitBreaker to the
shared CircuitBreakerTrait from common. Maps synchronous methods
(allow_request, record_success, etc.) to the async trait interface and
converts CircuitState variants to common::CircuitBreakerState.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
43f0fa90fc feat(common): add CircuitBreakerTrait for shared circuit breaker interface
Define an async trait that abstracts the circuit breaker state machine
(Closed -> Open -> HalfOpen) so different implementations can be used
polymorphically. Implement the trait for the existing tokio::Mutex-based
CircuitBreaker struct by delegating to its existing async methods.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
9693c7c590 refactor(ml): move Adam optimizer from lib.rs to optimizers/adam.rs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
1c940567ca refactor(adaptive-strategy): remove noisy hardcoded config eprintln warnings
Remove 8 warning prints (tracing::warn! and eprintln!) from Default impls
in config.rs. These fired on every test run and default construction,
creating noise. The migration notice in the module-level comment remains
as documentation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
64fa11b6d5 refactor(adaptive-strategy): remove dead code from execution, risk, and model modules
- execution/mod.rs: prefix 18 unused struct fields with _ (SlippageTracker,
  SmartOrderRouter, TWAP, VWAP, MarketImpactModel fields)
- risk/mod.rs: prefix 5 unused PnLTracker/RiskMetricsCalculator fields,
  remove #[allow(dead_code)] from DrawdownCalculator (fields are used),
  delete entirely unused CorrelationMatrix struct
- models/traditional.rs: prefix config/ready on 4 stub model structs
- models/deep_learning.rs: prefix config/ready on 3 stub model structs
- 80/80 tests pass, zero warnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
0e1d02bc82 refactor(adaptive-strategy): remove dead code from kelly_position_sizer
- Delete dead methods: calculate_base_kelly, calculate_variance (never called)
- Delete unused enum variants: VolatilityModelType::Garch/RangeBased/Realized
- Prefix 30+ unused struct fields with _ instead of #[allow(dead_code)]
- Remove all #[allow(dead_code)] attributes (24 total removed)
- Make calculate_win_loss_stats pub (used in tests)
- 80/80 tests pass, zero warnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
98c3ffa4df refactor(common): remove confusing aliased re-exports
Remove unused aliased re-exports from common/src/lib.rs:
- BarEventFromMarketData, MarketDataEventFromMarketData,
  OrderBookEventFromMarketData, QuoteEventFromMarketData,
  TradeEventFromMarketData (all unused, conflicted with types:: exports)
- ResilienceCircuitBreaker (unused alias for resilience::CircuitBreaker
  struct, conflicted with traits::CircuitBreaker trait)
- Also removes BarInterval and NewsEvent root re-exports (unused from
  root, accessible via common::market_data::*)

Users should import market_data types via common::market_data::* and
the resilience CircuitBreaker struct via common::resilience::CircuitBreaker.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
fd1b60bbf5 refactor: unify ModelType into common/model_types.rs
Consolidate 4 separate ModelType enum definitions (ml 15 variants,
model_loader 7, campaign 2, job_spawner 4) into a single canonical
definition in common/src/model_types.rs with the union of all variants
and all methods (file_extension, as_str, to_db_string, weight, from_str,
Display).

- ml/src/lib.rs: replace 15-variant enum with re-export
- model_loader/src/lib.rs: replace 7-variant enum with re-export,
  update PascalCase names (Dqn->DQN, Tft->TFT, etc)
- ml/hyperopt/campaign.rs: replace 2-variant enum with re-export
- services/ml_training_service/job_spawner.rs: replace 4-variant enum
  with re-export, MAMBA2->MAMBA
- Remove orphan impl ToString in ml/observability/metrics.rs (Display
  now provided by canonical type)
- Update backtesting_service and model_loader tests for new names

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:39:26 +01:00
jgrusewski
36a560ccb3 refactor(ml): remove stub ErrorCategory, use common::error::ErrorCategory
The ml crate had a stub ErrorCategory with only 1 variant (System).
Replace it with a re-export of the canonical 24-variant ErrorCategory
from common::error. Also rename the unused ErrorCategory in
data/src/providers/common.rs to ProviderErrorCategory to avoid
name collision.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:35:42 +01:00
jgrusewski
d2e6a78bab refactor: extract shared TLS types (TlsProtocolVersion, UserRole, ClientIdentity) to common/
Move identical TLS type definitions from 4 service crates into
common/src/tls.rs, eliminating ~435 lines of duplicated code.
Each service retains its own TlsConfig struct and validation logic
(async vs sync, delegated vs monolithic) while sharing the type
definitions. Services re-export the types for backward compatibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:35:42 +01:00
jgrusewski
34215f7c7e refactor(api_gateway): rename ConfigError to GatewayConfigError to avoid collision with config crate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:35:42 +01:00
jgrusewski
6afe9bab02 refactor(ml): consolidate OrderType into common/action.rs
Deduplicate four identical OrderType enums (Market/LimitMaker/IoC) into a
single definition at ml/src/common/action.rs with all methods from all copies
(transaction_cost, cost_bps, cost_decimal, from_index, Display). Original
locations now re-export via `pub use crate::common::action::OrderType`.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:35:42 +01:00
jgrusewski
2775d60c25 test(ml): add DQN + PPO checkpoint roundtrip integration tests
Add 6 integration tests that verify model weights survive a full
checkpoint cycle (serialize -> save to disk -> load -> predict):

- DQN raw Q-network weight roundtrip via safetensors
- DQN adapter roundtrip via DqnInferenceAdapter::from_checkpoint
- DQN CheckpointManager + Checkpointable trait flow
- PPO actor/critic checkpoint roundtrip with exact output comparison
- PPO inference after checkpoint load (probability validation)
- PPO adapter deterministic prediction verification

Fix a bug in DQN::load_from_safetensors where inserting new Var
objects into the VarMap HashMap left the Linear layers pointing at
stale data. The fix uses VarMap::load() which correctly updates
existing Vars in-place via Var::set(), preserving the shared
Arc<RwLock<Storage>> between VarMap entries and Linear layer tensors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:35:34 +01:00
jgrusewski
c431718027 fix(liquid): add backbone dim validation and negative dt guard
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:28:35 +01:00
jgrusewski
de30a6581e test(liquid): verify gradient flow through CfC v2 cells
Adds two gradient verification tests: test_cfc_gradient_flow confirms
backprop produces non-empty gradients for all parameters, and
test_cfc_optimizer_step_reduces_loss runs 10 AdamW steps and verifies
MSE loss decreases, proving the full CfC v2 compute graph is
differentiable end-to-end.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:21:24 +01:00
jgrusewski
a253d794c3 feat(liquid): add CandleCfCNetwork with full sequence processing
Wraps CfCCell with output projection for end-to-end sequence processing.
forward_sequence unrolls the cell over [batch, seq_len, features] input
and projects the final hidden state to [batch, output_size]. Includes
forward() convenience method with default dt=0.01 for UnifiedTrainable
compatibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:17:03 +01:00
jgrusewski
fe966ad028 feat(liquid): add CfC v2 cell with closed-form exponential update
Implements CfCCell with the core h(t+dt) = h*decay + f*(1-decay) update
rule where decay = exp(-dt/tau) and tau is a learned sigmoid-scaled time
constant. Uses manual_sigmoid for CUDA compatibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 23:12:55 +01:00
jgrusewski
de236c3798 feat(liquid): add BackboneMLP for CfC v2 cells
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 22:55:52 +01:00
jgrusewski
8b74a9a42e docs: add production hardening implementation plan (53 tasks, 5 phases)
Phase 1: ML pipeline verification (checkpoint roundtrip, feature extraction)
Phase 2: Service production logic (hardcoded values, stub responses)
Phases 3-5: Backtesting, ML crate TODOs, infrastructure/security/cleanup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 22:51:56 +01:00
jgrusewski
c4514d7a4f fix(liquid): add PartialEq derives and fix Cuda device fallback semantics
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 22:46:48 +01:00
jgrusewski
65a938bac8 feat(liquid): add CfC v2 training config and DeviceConfig types
Add candle_cfc module with CfCTrainConfig (Candle training path) and
DeviceConfig (CPU/CUDA/Auto device selection). This is the foundation
for the Liquid CfC v2 differentiable training implementation, parallel
to the existing FixedPoint inference path in cells.rs/network.rs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 22:35:10 +01:00
jgrusewski
340ec0d68f docs: add production hardening design (53 tasks, 5 phases)
Covers all TODO/FIXME items across workspace, checkpoint roundtrip
tests, feature extraction pipeline tests, and infrastructure cleanup.
No overlap with dedup-cleanup or liquid-cfc plans.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 22:33:08 +01:00