2c43296c2c
Iteration 1 of the Stage-1 "R-based signal quality" cycle (spec 0065): a strategy's signal quality, measured in R on its unsized bias stream, feed-forward. New discrete-trade machinery, NOT a SimBroker extension. What lands: - exposure -> bias (refs #126): the Exposure node/type/file/output-field renamed to Bias (computation unchanged: clamp(signal/scale,-1,+1); the SEMANTICS change — the output is the unsized strategy bias, sizing leaves the strategy). Scoped to the semantic core; behaviour-preserving cosmetics are deferred (see below). - stop-rule nodes (refs #119): VolStop = k*EMA(|price - prev_price|) (one fused node; the volatility that defines 1R, close-to-close — true-range ATR deferred, needs OHLC) + FixedStop (constant, the test fixture / fixed-vs-vol structural-axis sibling). - PositionManagement (refs #127): the stateful heart. Latches the entry-cycle stop distance as the FROZEN R-denominator (never re-read), marks/exits no-look-ahead like SimBroker (a position earns from the next cycle; an exit realises against the cycle's close), and emits ONE dense per-cycle R-record (C8). Stop-outs are NOT capped at -1R (a gap through the stop realises R < -1 — the honest loss tail); R is computed size-invariantly (size = (exit-entry)*dir / latched_dist cancels). The trade ledger is the rows where closed_this_cycle; the R-equity is cum_realized + unrealized; a position open at window end is the last row (open=true) — explicit, never silent MtM. - summarize_r + RMetrics (refs #129): the post-run fold (NOT an in-graph node — recorders drain post-run). E[R], win-rate, profit-factor, avg win/loss R, by-trade max R-drawdown, n_open_at_end (window-end force-close). SQN / conviction terciles / net-of-cost / RunMetrics.r are iteration 2. Design adversarially hardened before implementation (12-juror refute panel; decisions on #117). Ratified implementer deviations from the plan snippet, verified by hand: - col-4 `direction` tracks the OPEN position at cycle end (window-end synthesis; names the reopened leg on a reversal), falling back to the closed trade's dir only when flat. summarize_r does not read col 4; the R-metrics are unaffected. - .named("exposure") kept on the 4 previously-unnamed Bias nodes so the auto-derived param-path stays exposure.scale (no manifest/dir-name drift) — the unnamed nodes would otherwise flip to bias.scale. - intra-doc links [`Exposure`] -> [`Bias`] in sim_broker/latch + the sample-model test pin (cosmetic, behaviour-neutral; broken intra-doc links fail cargo doc). - the E2E drives a full bootstrapped Harness (stronger than the plan's direct-node drive — exercises the real cross-crate producer->consumer seam). Deferred (behaviour-preserving, separate cosmetic pass — NOT this iteration): RunMetrics.exposure_sign_flips / Metric::ExposureSignFlips, SimBroker/LongOnly "exposure" input ports, the "exposure" tap/trace names, and the .named("exposure") instance labels. Iteration 2: the Sizer seam, the RiskExecutor composite (+ the Veto documented-seam), summarize_r enrichment, RunMetrics.r, and the CLI/recording surface. Verification (orchestrator-run, not agent-claimed): - cargo build --workspace: clean. - cargo test --workspace: all green, 0 failed (incl. the new bias/stop_rule/ position_management unit tests, the summarize_r arithmetic tests, and the stage1_r_e2e capstone + layout guard). - cargo clippy --workspace --all-targets -- -D warnings: clean (exit 0). - Keystone RED tests pass: no_lookahead_bias_exit_realises_the_held_move, stop_out_is_not_capped_at_minus_one_r, no_gap_stop_is_exactly_minus_one_r, reversal_closes_one_leg_and_reopens, open_at_window_end_is_carried_on_the_last_row. refs #117 #119 #126 #127 #129
173 lines
6.6 KiB
Rust
173 lines
6.6 KiB
Rust
//! `SimBroker` — the sim-optimal broker (class (a) of C10): deterministic,
|
|
//! frictionless, perfect-fill. Consumes an exposure stream (slot 0) + a price
|
|
//! stream (slot 1) and integrates the return earned by the exposure held INTO
|
|
//! each cycle (decided at t-1) into a cumulative synthetic pip-equity output.
|
|
//! Measures signal quality, not execution-modelled P&L.
|
|
|
|
use aura_core::{Cell, Ctx, FieldSpec, Firing, Node, NodeSchema, PortSpec, PrimitiveBuilder, ScalarKind};
|
|
|
|
/// Integrates `exposure * price-return` into cumulative pips. `pip_size` is
|
|
/// per-instrument reference metadata (beside the hot path, C7/C15), held here,
|
|
/// never streamed.
|
|
///
|
|
/// # Input slots
|
|
///
|
|
/// Two `f64` inputs, **order is load-bearing** (both are `f64`, so a swapped
|
|
/// wiring is *not* caught at bootstrap — it would silently produce a wrong
|
|
/// equity curve):
|
|
///
|
|
/// - **slot 0 — exposure** ∈ [-1, +1] (the strategy's intent, e.g. from
|
|
/// [`Bias`](crate::Bias)).
|
|
/// - **slot 1 — price** (the instrument price the exposure is marked against).
|
|
///
|
|
/// # Firing and warm-up
|
|
///
|
|
/// Both inputs are [`Firing::Any`](aura_core::Firing::Any), so the broker fires
|
|
/// on **every price-fresh cycle** (price is typically the source tick). A
|
|
/// not-yet-warmed exposure leg is read as flat `0.0`, so the broker emits an
|
|
/// equity row from the **first** price tick, reading `0.0` until the exposure
|
|
/// leg produces its first value — the recorded curve therefore has one row per
|
|
/// price cycle, with leading `0.0`s during warm-up, not one row per exposure.
|
|
///
|
|
/// # Output
|
|
///
|
|
/// One `f64` column, the cumulative pip equity (a producer; tap it with a
|
|
/// recording sink to persist the curve).
|
|
pub struct SimBroker {
|
|
pip_size: f64,
|
|
prev_price: Option<f64>,
|
|
prev_exposure: f64, // exposure held into this cycle (decided at t-1); 0.0 = flat
|
|
cum: f64, // cumulative pips
|
|
out: [Cell; 1],
|
|
}
|
|
|
|
impl SimBroker {
|
|
/// Build a sim-optimal broker for an instrument whose pip is `pip_size`
|
|
/// (price units per pip; must be > 0).
|
|
pub fn new(pip_size: f64) -> Self {
|
|
assert!(pip_size > 0.0, "SimBroker pip_size must be > 0");
|
|
Self {
|
|
pip_size,
|
|
prev_price: None,
|
|
prev_exposure: 0.0,
|
|
cum: 0.0,
|
|
out: [Cell::from_f64(0.0)],
|
|
}
|
|
}
|
|
|
|
/// The param-generic recipe for a blueprint primitive. `pip_size` is per-instrument
|
|
/// metadata (C10/C15), not a tunable param — it is captured by the closure, not
|
|
/// injected; the node declares no params.
|
|
pub fn builder(pip_size: f64) -> PrimitiveBuilder {
|
|
PrimitiveBuilder::new(
|
|
"SimBroker",
|
|
NodeSchema {
|
|
inputs: vec![
|
|
PortSpec { kind: ScalarKind::F64, firing: Firing::Any, name: "exposure".into() },
|
|
PortSpec { kind: ScalarKind::F64, firing: Firing::Any, name: "price".into() },
|
|
],
|
|
output: vec![FieldSpec { name: "equity".into(), kind: ScalarKind::F64 }],
|
|
params: vec![],
|
|
},
|
|
move |_| Box::new(SimBroker::new(pip_size)),
|
|
)
|
|
}
|
|
}
|
|
|
|
impl Node for SimBroker {
|
|
fn lookbacks(&self) -> Vec<usize> {
|
|
vec![1, 1]
|
|
}
|
|
|
|
fn eval(&mut self, ctx: Ctx<'_>) -> Option<&[Cell]> {
|
|
let price = ctx.f64_in(1);
|
|
if price.is_empty() {
|
|
return None; // no price yet — nothing to mark
|
|
}
|
|
let price = price[0];
|
|
let expo = ctx.f64_in(0).get(0).unwrap_or(0.0); // flat until exposure warms up
|
|
if let Some(pp) = self.prev_price {
|
|
self.cum += self.prev_exposure * (price - pp) / self.pip_size;
|
|
}
|
|
self.prev_price = Some(price);
|
|
self.prev_exposure = expo; // update AFTER taking PnL — no look-ahead (C2)
|
|
self.out[0] = Cell::from_f64(self.cum);
|
|
Some(&self.out)
|
|
}
|
|
|
|
fn label(&self) -> String {
|
|
format!("SimBroker({})", self.pip_size)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use aura_core::{AnyColumn, Scalar, Timestamp};
|
|
|
|
fn two_f64_inputs() -> Vec<AnyColumn> {
|
|
vec![
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
AnyColumn::with_capacity(ScalarKind::F64, 1),
|
|
]
|
|
}
|
|
|
|
// Drive one broker cycle by hand: optionally push an exposure into slot 0
|
|
// (None models a cycle where the exposure chain has not warmed up — slot 0
|
|
// stays empty) and a price into slot 1, then eval and return the equity.
|
|
fn step(b: &mut SimBroker, inputs: &mut [AnyColumn], expo: Option<f64>, price: f64) -> f64 {
|
|
if let Some(e) = expo {
|
|
inputs[0].push(Scalar::f64(e)).unwrap();
|
|
}
|
|
inputs[1].push(Scalar::f64(price)).unwrap();
|
|
match b.eval(Ctx::new(inputs, Timestamp(0))) {
|
|
Some([c]) => c.f64(),
|
|
other => panic!("expected Some([F64]), got {other:?}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn sim_broker_integrates_lagged_exposure_times_return() {
|
|
let mut b = SimBroker::new(1.0);
|
|
let mut inputs = two_f64_inputs();
|
|
assert_eq!(step(&mut b, &mut inputs, Some(0.5), 100.0), 0.0); // no prev price
|
|
assert_eq!(step(&mut b, &mut inputs, Some(0.5), 110.0), 5.0); // 0.5*(110-100)
|
|
assert_eq!(step(&mut b, &mut inputs, Some(-1.0), 108.0), 4.0); // +0.5*(108-110) = -1
|
|
assert_eq!(step(&mut b, &mut inputs, Some(-1.0), 100.0), 12.0); // +(-1)*(100-108) = +8
|
|
}
|
|
|
|
#[test]
|
|
fn sim_broker_no_lookahead() {
|
|
let mut b = SimBroker::new(1.0);
|
|
let mut inputs = two_f64_inputs();
|
|
step(&mut b, &mut inputs, Some(1.0), 100.0);
|
|
// exposure flips to 0.0 THIS cycle, but the PnL must use the 1.0 held
|
|
// into it: 1.0*(110-100) = 10. Using the fresh 0.0 would give 0.
|
|
assert_eq!(step(&mut b, &mut inputs, Some(0.0), 110.0), 10.0);
|
|
}
|
|
|
|
#[test]
|
|
fn sim_broker_is_flat_during_warmup() {
|
|
let mut b = SimBroker::new(1.0);
|
|
let mut inputs = two_f64_inputs();
|
|
// exposure never pushed (slot 0 empty) -> treated as flat; equity stays 0
|
|
assert_eq!(step(&mut b, &mut inputs, None, 100.0), 0.0);
|
|
assert_eq!(step(&mut b, &mut inputs, None, 110.0), 0.0);
|
|
assert_eq!(step(&mut b, &mut inputs, None, 90.0), 0.0);
|
|
}
|
|
|
|
#[test]
|
|
fn sim_broker_first_cycle_has_no_pnl() {
|
|
let mut b = SimBroker::new(1.0);
|
|
let mut inputs = two_f64_inputs();
|
|
assert_eq!(step(&mut b, &mut inputs, Some(1.0), 100.0), 0.0); // no prev price to mark
|
|
}
|
|
|
|
#[test]
|
|
fn input_slots_are_named_exposure_price() {
|
|
let b = SimBroker::builder(1.0);
|
|
let names: Vec<&str> = b.schema().inputs.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["exposure", "price"]);
|
|
}
|
|
}
|