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
98 lines
3.3 KiB
Rust
98 lines
3.3 KiB
Rust
//! `Bias` — shapes a raw signal score into a bounded, UNSIGNED-magnitude directional
|
|
//! bias (C10). The strategy's primary output: one f64 input, one f64 output
|
|
//! `clamp(signal / scale, -1, +1)`. Sign is direction, magnitude is (optional)
|
|
//! conviction; the output is UNSIZED — sizing leaves the strategy (downstream Sizer).
|
|
//! `scale` sets which signal magnitude maps to full conviction.
|
|
use aura_core::{
|
|
Cell, Ctx, FieldSpec, Firing, Node, NodeSchema, ParamSpec, PortSpec, PrimitiveBuilder,
|
|
ScalarKind,
|
|
};
|
|
|
|
/// Bounded bias from a raw signal score: `clamp(signal / scale, -1.0, +1.0)`.
|
|
/// Emits `None` until its input is present (warm-up filter, C8).
|
|
pub struct Bias {
|
|
scale: f64,
|
|
out: [Cell; 1],
|
|
}
|
|
|
|
impl Bias {
|
|
/// Build a bias node with saturation magnitude `scale` (must be > 0).
|
|
pub fn new(scale: f64) -> Self {
|
|
assert!(scale > 0.0, "Bias scale must be > 0");
|
|
Self { scale, out: [Cell::from_f64(0.0)] }
|
|
}
|
|
|
|
/// The param-generic recipe for a blueprint primitive: declares `scale` and builds
|
|
/// through `Bias::new` (the single sizing/validation gate; the slice is
|
|
/// kind-checked before `build` runs, so the typed read is total).
|
|
pub fn builder() -> PrimitiveBuilder {
|
|
PrimitiveBuilder::new(
|
|
"Bias",
|
|
NodeSchema {
|
|
inputs: vec![PortSpec { kind: ScalarKind::F64, firing: Firing::Any, name: "signal".into() }],
|
|
output: vec![FieldSpec { name: "bias".into(), kind: ScalarKind::F64 }],
|
|
params: vec![ParamSpec { name: "scale".into(), kind: ScalarKind::F64 }],
|
|
},
|
|
|p| Box::new(Bias::new(p[0].f64())),
|
|
)
|
|
}
|
|
}
|
|
|
|
impl Node for Bias {
|
|
fn lookbacks(&self) -> Vec<usize> {
|
|
vec![1]
|
|
}
|
|
|
|
fn eval(&mut self, ctx: Ctx<'_>) -> Option<&[Cell]> {
|
|
let w = ctx.f64_in(0);
|
|
if w.is_empty() {
|
|
return None; // not yet warmed up (C8 filter)
|
|
}
|
|
self.out[0] = Cell::from_f64((w[0] / self.scale).clamp(-1.0, 1.0));
|
|
Some(&self.out)
|
|
}
|
|
|
|
fn label(&self) -> String {
|
|
format!("Bias({})", self.scale)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use aura_core::{AnyColumn, Scalar, Timestamp};
|
|
|
|
#[test]
|
|
fn bias_clamps_to_unit_band() {
|
|
let mut e = Bias::new(0.5);
|
|
let mut inputs = vec![AnyColumn::with_capacity(ScalarKind::F64, 1)];
|
|
// (raw signal, expected clamped bias) for scale 0.5
|
|
let cases = [
|
|
(0.1_f64, 0.2_f64), // within band
|
|
(0.5, 1.0), // at the high edge
|
|
(1.0, 1.0), // saturates high
|
|
(-0.1, -0.2), // within band, negative
|
|
(-1.0, -1.0), // saturates low
|
|
];
|
|
for (sig, want) in cases {
|
|
inputs[0].push(Scalar::f64(sig)).unwrap();
|
|
assert_eq!(
|
|
e.eval(Ctx::new(&inputs, Timestamp(0))),
|
|
Some([Cell::from_f64(want)].as_slice())
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn bias_is_none_until_input_present() {
|
|
let mut e = Bias::new(0.5);
|
|
let inputs = vec![AnyColumn::with_capacity(ScalarKind::F64, 1)];
|
|
assert_eq!(e.eval(Ctx::new(&inputs, Timestamp(0))), None);
|
|
}
|
|
|
|
#[test]
|
|
fn input_slot_is_named_signal() {
|
|
assert_eq!(Bias::builder().schema().inputs[0].name, "signal");
|
|
}
|
|
}
|