Files
foxhunt/crates/ml/tests/paper_trading_integration_test.rs
jgrusewski 66bc8d12e5 refactor: remove configurable state_dim — use STATE_DIM constant everywhere
Remove pub state_dim field from DQNConfig and GpuReplayBufferConfig; remove the
state_dim field from GpuExperienceCollector. Replace all reads with
ml_core::state_layout::STATE_DIM (and STATE_DIM_PADDED for cuBLAS-padded
strides). Checkpoint loading now validates saved state_dim against the
constant and hard-errors on mismatch. GpuAttentionConfig.state_dim is a
distinct attention-feature dim and is left untouched.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 15:29:05 +02:00

210 lines
6.7 KiB
Rust

#![allow(
clippy::assertions_on_constants,
clippy::assertions_on_result_states,
clippy::clone_on_copy,
clippy::decimal_literal_representation,
clippy::doc_markdown,
clippy::empty_line_after_doc_comments,
clippy::field_reassign_with_default,
clippy::get_unwrap,
clippy::identity_op,
clippy::inconsistent_digit_grouping,
clippy::indexing_slicing,
clippy::integer_division,
clippy::len_zero,
clippy::let_underscore_must_use,
clippy::manual_div_ceil,
clippy::manual_let_else,
clippy::manual_range_contains,
clippy::modulo_arithmetic,
clippy::needless_range_loop,
clippy::non_ascii_literal,
clippy::redundant_clone,
clippy::shadow_reuse,
clippy::shadow_same,
clippy::shadow_unrelated,
clippy::single_match_else,
clippy::str_to_string,
clippy::string_slice,
clippy::tests_outside_test_module,
clippy::too_many_lines,
clippy::unnecessary_wraps,
clippy::unseparated_literal_suffix,
clippy::use_debug,
clippy::useless_vec,
clippy::wildcard_enum_match_arm,
clippy::else_if_without_else,
clippy::expect_used,
clippy::missing_const_for_fn,
clippy::similar_names,
clippy::type_complexity,
clippy::collapsible_else_if,
clippy::doc_lazy_continuation,
clippy::items_after_test_module,
clippy::map_clone,
clippy::multiple_unsafe_ops_per_block,
clippy::unwrap_or_default,
clippy::assign_op_pattern,
clippy::needless_borrow,
clippy::println_empty_string,
clippy::unnecessary_cast,
clippy::used_underscore_binding,
clippy::create_dir,
clippy::implicit_saturating_sub,
clippy::exit,
clippy::expect_fun_call,
clippy::too_many_arguments,
clippy::unnecessary_map_or,
clippy::unwrap_used,
dead_code,
unused_imports,
unused_variables,
clippy::cloned_ref_to_slice_refs,
clippy::neg_multiply,
clippy::while_let_loop,
clippy::bool_assert_comparison,
clippy::excessive_precision,
clippy::trivially_copy_pass_by_ref,
clippy::op_ref,
clippy::redundant_closure,
clippy::unnecessary_lazy_evaluations,
clippy::if_then_some_else_none,
clippy::unnecessary_to_owned,
clippy::single_component_path_imports,
)]
//! Paper trading pipeline integration test.
//!
//! Replays synthetic price data through the full pipeline:
//! Feature extraction -> Ensemble -> TradeSignal -> PaperBroker -> PnL
#![allow(unused_crate_dependencies)]
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
#![allow(clippy::indexing_slicing)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::tests_outside_test_module)]
use ml::dqn::dqn::DQNConfig;
use ml::ensemble::adapters::dqn::DqnInferenceAdapter;
use ml::ensemble::adapters::ppo::PpoInferenceAdapter;
use ml::ensemble::inference_adapter::{FeatureVector, ModelInferenceAdapter};
use ml::ensemble::inference_ensemble::InferenceEnsemble;
use ml::ensemble::signal::TradeSignal;
use ml::paper_trading::broker::PaperBroker;
use ml::paper_trading::pnl_tracker::PnLTracker;
use ml::ppo::ppo::PPOConfig;
#[test]
fn test_paper_trading_pipeline_synthetic_data() {
// 1. Create DQN adapter with small config
let dqn_config = DQNConfig {
num_actions: 3, // buy / hold / sell
hidden_dims: vec![32, 32],
..Default::default()
};
let dqn_adapter =
DqnInferenceAdapter::new(dqn_config).expect("DQN adapter should initialise");
assert!(dqn_adapter.is_ready(), "DQN adapter must be ready");
// 2. Create PPO adapter with matching config
let ppo_config = PPOConfig {
state_dim: 51,
num_actions: 3,
policy_hidden_dims: vec![32, 32],
value_hidden_dims: vec![32, 32],
..Default::default()
};
let ppo_adapter =
PpoInferenceAdapter::new(ppo_config).expect("PPO adapter should initialise");
assert!(ppo_adapter.is_ready(), "PPO adapter must be ready");
// 3. Build InferenceEnsemble with both adapters
let adapters: Vec<Box<dyn ModelInferenceAdapter>> =
vec![Box::new(dqn_adapter), Box::new(ppo_adapter)];
let ensemble = InferenceEnsemble::new(adapters);
assert_eq!(ensemble.ready_count(), 2, "Both models must be ready");
// 4. Create PaperBroker with $100k cash and 1bps slippage
let mut broker = PaperBroker::new(100_000.0, 0.0001);
// 5. Create PnLTracker with 252-bar window
let mut pnl_tracker = PnLTracker::new(252);
// 6. Simulate 100 bars of synthetic price data
let mut price = 1.0850_f64;
let num_bars = 100_usize;
for i in 0..num_bars {
// Create synthetic feature vector (51-dim)
let values: Vec<f64> = (0..51)
.map(|j| {
// Deterministic pseudo-features based on price and bar index
let base = price * (1.0 + 0.001 * ((j as f64) - 25.0));
base * (1.0 + 0.0001 * (i as f64))
})
.collect();
let fv = FeatureVector {
values,
timestamp: 1_700_000_000_000_000 + (i as i64 * 60_000_000), // 1-min bars
};
// Get ensemble prediction
let prediction = ensemble
.predict(&fv)
.expect("Ensemble prediction should succeed");
// Convert to trade signal
let signal = TradeSignal::from_prediction(&prediction, "6E.FUT");
// Execute through broker
let _fill = broker.execute_signal(&signal, price);
// Record equity
let equity = broker.equity(price);
pnl_tracker.record_equity(equity);
// Random-walk the price (deterministic using bar index)
price += 0.0001 * ((i % 7) as f64 - 3.0);
}
// 7. Assertions
let sharpe = pnl_tracker.rolling_sharpe();
let drawdown = pnl_tracker.max_drawdown();
let num_trades = broker.num_trades();
let num_obs = pnl_tracker.num_observations();
let cum_return = pnl_tracker.cumulative_return();
use tracing::info;
info!(num_bars, num_trades, sharpe, drawdown, cum_return, final_equity = broker.equity(price), price, num_obs, "Paper Trading Pipeline Summary");
// Sharpe ratio should be finite (not NaN/Inf)
assert!(
sharpe.is_finite(),
"Sharpe ratio must be finite, got {}",
sharpe
);
// Drawdown should be finite and bounded [0, 1]
assert!(
drawdown.is_finite() && drawdown <= 1.0,
"Drawdown must be finite and <= 1.0, got {}",
drawdown
);
// At least some trades should have been executed
assert!(
num_trades > 0,
"Expected at least 1 trade, got {}",
num_trades
);
// PnL tracker should have recorded all 100 observations
assert!(
num_obs >= num_bars,
"Expected >= {} observations, got {}",
num_bars, num_obs
);
}