diff --git a/apps/stock/engine/src/api/replay.rs b/apps/stock/engine/src/api/replay.rs index fb662d22..2392a061 100644 --- a/apps/stock/engine/src/api/replay.rs +++ b/apps/stock/engine/src/api/replay.rs @@ -5,6 +5,7 @@ use crate::financial::{ contract::*, matching::OrderStatus, replay::*, + reporting::ReportingFacts, result::{project, FinancialProjection}, }; use napi::{Error, Result}; @@ -60,6 +61,15 @@ struct ProjectionResult<'a> { projection: FinancialProjection<'a>, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ReportResult<'a> { + #[serde(flatten)] + financial: ProjectionResult<'a>, + reporting_version: Version, + reporting: &'a ReportingFacts, +} + fn error(error: impl std::fmt::Display) -> Error { Error::from_reason(error.to_string()) } @@ -204,6 +214,31 @@ impl ReplayHost { }) .map_err(error) } + + pub fn report(&self, input: String) -> Result { + let identity: Identity = parse(&input)?; + self.check(&identity)?; + let replay = self.replay.as_ref().unwrap(); + let reporting = replay.reporting().map_err(error)?; + serde_json::to_string(&ReportResult { + financial: ProjectionResult { + format: "report", + projection_version: Version, + financial_version: Version, + identity: &self.identity, + status: "complete", + manifest: &self.manifest, + policy: &self.config, + view: view(replay)?, + limitations: replay.limitations(), + model_limitations: replay.model_limitations(), + projection: project(replay.financial().ledger()).map_err(error)?, + }, + reporting_version: Version, + reporting, + }) + .map_err(error) + } } // NAPI's impl macro requires literal method annotations. Keep this tiny @@ -236,6 +271,10 @@ impl FinancialReplaySession { self.0.project(input) } #[napi] + pub fn report(&self, input: String) -> Result { + self.0.report(input) + } + #[napi] pub fn dispose(&mut self) { self.0.dispose(); } @@ -333,6 +372,13 @@ mod tests { final_result ); let projected: Value = serde_json::from_str(&compact).unwrap(); + let report = native.report(identity.to_string()).unwrap(); + assert_eq!(native.report(identity.to_string()).unwrap(), report); + assert_eq!(native.project(identity.to_string()).unwrap(), compact); + assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before); + let reported: Value = serde_json::from_str(&report).unwrap(); + assert_eq!(reported["projection"], projected["projection"]); + assert_eq!(reported["reporting"]["occupiedMs"], "120000"); assert_eq!(projected["view"], final_result["view"]); assert!(projected.get("receipts").is_none()); let load: Load = parse(fixture).unwrap(); @@ -341,8 +387,13 @@ mod tests { projected["projection"], serde_json::to_value(project(restored.financial().ledger()).unwrap()).unwrap() ); + assert_eq!( + reported["reporting"], + serde_json::to_value(restored.reporting().unwrap()).unwrap() + ); native.dispose(); assert!(native.finalize(identity.to_string()).is_err()); assert!(native.project(identity.to_string()).is_err()); + assert!(native.report(identity.to_string()).is_err()); } } diff --git a/apps/stock/engine/src/financial/mod.rs b/apps/stock/engine/src/financial/mod.rs index f3992c5a..01020b77 100644 --- a/apps/stock/engine/src/financial/mod.rs +++ b/apps/stock/engine/src/financial/mod.rs @@ -6,6 +6,7 @@ pub mod contract; pub mod ledger; pub mod matching; pub mod replay; +pub mod reporting; pub mod result; pub mod risk; pub mod scalar; @@ -28,6 +29,9 @@ mod replay_tests; #[cfg(test)] mod result_tests; +#[cfg(test)] +mod reporting_tests; + // Exercise the pure host adapter without linking every legacy NAPI export. #[cfg(test)] #[path = "../api/replay.rs"] diff --git a/apps/stock/engine/src/financial/replay.rs b/apps/stock/engine/src/financial/replay.rs index b0c199a4..34dca015 100644 --- a/apps/stock/engine/src/financial/replay.rs +++ b/apps/stock/engine/src/financial/replay.rs @@ -13,6 +13,7 @@ use super::{ contract::*, matching::*, + reporting::{Reporting, ReportingFacts}, scalar::{Posting, ScalarError}, }; use serde::{Deserialize, Serialize}; @@ -214,6 +215,7 @@ pub struct Replay { status: ReplayStatus, submissions: Vec, matching: MatchingAccount, + reporting: Reporting, } impl Replay { @@ -230,6 +232,12 @@ impl Replay { .iter() .map(|s| s.series_id.clone()) .collect(); + let reporting = Reporting::new( + &config.matching.risk.ledger.risk_session, + &config.risk_boundaries, + &input.bounds, + matching.ledger().cash(), + ); Ok(Self { input, config, @@ -243,6 +251,7 @@ impl Replay { status: ReplayStatus::Running, submissions: Vec::new(), matching, + reporting, }) } fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) { @@ -652,6 +661,12 @@ impl Replay { pub fn model_limitations(&self) -> &'static [&'static str] { MODEL_LIMITATIONS } + pub fn reporting(&self) -> Result<&ReportingFacts, &str> { + if self.status != ReplayStatus::Complete { + return Err("only a complete replay can report successfully"); + } + self.reporting.facts() + } fn command( &mut self, @@ -659,11 +674,13 @@ impl Replay { key: EventKey, body: MatchingCommandBody, ) -> Result<(), ReplayError> { + let at = key.at; let out = self.matching.apply(&MatchingCommand { command_id: id(("replay", index)), key, body, })?; + self.reporting.committed(at, &out, self.matching.ledger()); if let AttemptStatus::Failed { diagnostic } = out.status { self.status = ReplayStatus::Failed { diagnostic }; } @@ -766,6 +783,7 @@ impl Replay { self.command(index, key, MatchingCommandBody::Finish)?; if self.status == ReplayStatus::Running { self.status = ReplayStatus::Complete; + self.reporting.finish(self.matching.ledger()); } } } @@ -782,6 +800,8 @@ impl Replay { while self.status == ReplayStatus::Running && processed < budget { let index = self.next_event; let event = self.events[index].clone(); + let at = event.key.at; + let observation = event.key.phase == EventPhase::Observation; self.next_event += 1; processed += 1; if let Err(error) = self.process(index, event) { @@ -789,6 +809,15 @@ impl Replay { diagnostic: error.to_string(), }; } + if observation + && self.status == ReplayStatus::Running + && self.events.get(self.next_event).is_none_or(|next| { + next.key.at != at || next.key.phase != EventPhase::Observation + }) + { + self.reporting + .after_observations(at, self.matching.ledger()); + } if let Some(barrier) = &self.pending { return Ok(ReplayStep::Decision(barrier.clone())); } diff --git a/apps/stock/engine/src/financial/replay_tests.rs b/apps/stock/engine/src/financial/replay_tests.rs index 4fbf7cc3..e7b340c9 100644 --- a/apps/stock/engine/src/financial/replay_tests.rs +++ b/apps/stock/engine/src/financial/replay_tests.rs @@ -570,6 +570,158 @@ fn restore_before_and_after_every_decision_and_at_complete() { target(&mut uninterrupted, &b, "2"); } assert_eq!(r.checkpoint(), uninterrupted.checkpoint()); + assert_eq!(r.reporting().unwrap(), uninterrupted.reporting().unwrap()); +} + +fn reporting_boundary(name: &str, at: i64) -> RiskSessionIdentity { + RiskSessionIdentity { + calendar_id: id("account"), + calendar_revision: id("1"), + session_id: id(name), + starts_at: t(at), + } +} + +#[test] +fn two_session_marks_follow_observations_without_changing_earlier_risk_reset() { + let (mut input, mut config) = fixture(); + input.bounds.trade_start = t(0); + config.risk_boundaries = vec![ + reporting_boundary("risk2", 20), + reporting_boundary("risk3", 30), + ]; + let mut r = Replay::new(input, config).unwrap(); + assert!(r.reporting().is_err()); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + let b = next(&mut r).unwrap(); + assert_eq!(b.at, t(20)); + // Existing reset runs before the completed observation's13 mark. + assert_eq!( + Posting::from(r.financial().risk().state().daily_baseline), + p("9999.76") + ); + no_change(&mut r, &b); + complete(&mut r); + let facts = r.reporting().unwrap(); + assert_eq!(facts.initial_equity, p("10000")); + assert_eq!(facts.sessions.len(), 2); + assert_eq!(facts.sessions[0].session.session_id, id("risk1")); + assert_eq!(facts.sessions[0].period_start, t(0)); + assert_eq!(facts.sessions[0].period_end, t(20)); + assert_eq!(facts.sessions[0].equity, p("10001.76")); + assert_eq!(facts.sessions[1].equity, p("10005.76")); + assert!(!facts + .sessions + .iter() + .any(|s| s.partial_start || s.partial_end)); + assert_eq!(facts.occupied_ms, "20"); + assert_eq!(facts.elapsed_ms, "30"); +} + +#[test] +fn reporting_clips_warmup_initial_and_final_periods_and_deduplicates_exact_end() { + for exact_start in [false, true] { + for exact_end in [false, true] { + let (input, mut config) = fixture(); + config.risk_boundaries = vec![ + reporting_boundary("warmup", 5), + reporting_boundary("risk2", 20), + ]; + if exact_start { + config.risk_boundaries.push(reporting_boundary("start", 10)); + } + if exact_end { + config.risk_boundaries.push(reporting_boundary("end", 30)); + } + let mut r = Replay::new(input, config).unwrap(); + complete(&mut r); + let facts = r.reporting().unwrap(); + assert_eq!(facts.sessions.len(), 2); + assert_eq!( + facts.sessions[0].session.session_id, + id(if exact_start { "start" } else { "warmup" }) + ); + assert_eq!(facts.sessions[0].period_start, t(10)); + assert_eq!(facts.sessions[0].partial_start, !exact_start); + assert!(!facts.sessions[0].partial_end); + assert_eq!(facts.sessions[1].partial_end, !exact_end); + assert_eq!(facts.sessions[1].period_end, t(30)); + assert!(facts.sessions.iter().all(|s| s.equity == p("10000"))); + assert_eq!(facts.occupied_ms, "0"); + assert!(facts.occupied_intervals.is_empty()); + } + } +} + +#[test] +fn reporting_boundary_without_decision_and_terminal_stale_mark_use_only_available_facts() { + let (mut input, mut config) = fixture(); + config.risk_boundaries = vec![reporting_boundary("risk2", 15)]; + input.bars[2].available_at = t(31); // Final close15 is not available by end30. + let mut r = Replay::new(input, config).unwrap(); + let b = next(&mut r).unwrap(); + target(&mut r, &b, "2"); + complete(&mut r); + let facts = r.reporting().unwrap(); + assert_eq!(facts.sessions[0].period_end, t(15)); + assert_eq!(facts.sessions[0].equity, p("9999.76")); + // Last available authoritative mark is the open14, not the future close15. + assert_eq!(facts.sessions[1].equity, p("10003.76")); + assert_eq!( + facts.sessions[1].equity, + r.financial().ledger().equity().unwrap() + ); + assert_eq!(r.observations().count(), 2); +} + +#[test] +fn reporting_restore_every_event_including_partial_observation_groups() { + let (mut input, mut config) = fixture(); + input.series.push(series("Y-bars", "Y")); + input + .bars + .extend(input.bars.clone().into_iter().map(|mut bar| { + bar.series_id = id("Y-bars"); + bar.instrument_id = id("Y"); + bar + })); + config.matching.series.push(ExecutionSeries { + instrument_id: id("Y"), + series_id: id("Y-bars"), + mode: ExecutionMode::Open, + }); + config.risk_boundaries = vec![ + reporting_boundary("risk2", 20), + reporting_boundary("risk3", 30), + ]; + let mut uninterrupted = Replay::new(input.clone(), config.clone()).unwrap(); + while let Some(b) = next(&mut uninterrupted) { + target(&mut uninterrupted, &b, "2"); + } + let mut resumed = Replay::new(input.clone(), config.clone()).unwrap(); + loop { + let step = resumed.advance(1).unwrap(); + let cp = resumed.checkpoint(); + resumed = Replay::restore(input.clone(), config.clone(), &cp).unwrap(); + assert_eq!(resumed.checkpoint(), cp); + match step { + ReplayStep::Decision(b) => { + target(&mut resumed, &b, "2"); + resumed = + Replay::restore(input.clone(), config.clone(), &resumed.checkpoint()).unwrap(); + } + ReplayStep::Complete => break, + ReplayStep::Progress { .. } => {} + other => panic!("unexpected {other:?}"), + } + } + assert_eq!(uninterrupted.checkpoint(), resumed.checkpoint()); + assert_eq!( + uninterrupted.reporting().unwrap(), + resumed.reporting().unwrap() + ); + assert_eq!(resumed.reporting().unwrap().sessions.len(), 2); } #[test] fn altered_input_config_and_checkpoint_rejected() { @@ -808,6 +960,9 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() { config.matching.risk.fee_rate = nn("0"); config.matching.risk.max_daily_loss = pos("10"); config.matching.risk.max_drawdown_amount = pos("10"); + // A reporting sample uses the final observation-group equity without + // changing the existing sequential risk latch. + config.risk_boundaries.push(reporting_boundary("risk2", 20)); let mut permuted = input.clone(); permuted.bars.reverse(); let mut checkpoints = vec![]; @@ -847,6 +1002,11 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() { assert!(r.financial().risk().state().daily_halted); assert!(r.financial().risk().state().drawdown_halted); checkpoints.push(r.checkpoint()); + no_change(&mut r, &b); + complete(&mut r); + assert_eq!(r.reporting().unwrap().sessions[0].equity, p("10000")); + assert!(r.financial().risk().state().daily_halted); + assert!(r.financial().risk().state().drawdown_halted); } assert_eq!(checkpoints[0], checkpoints[1]); assert!(MODEL_LIMITATIONS diff --git a/apps/stock/engine/src/financial/reporting.rs b/apps/stock/engine/src/financial/reporting.rs new file mode 100644 index 00000000..565e3369 --- /dev/null +++ b/apps/stock/engine/src/financial/reporting.rs @@ -0,0 +1,238 @@ +//! Reporting-only facts sampled during the existing replay. This state cannot +//! submit financial commands and is rebuilt by the normal checkpoint restore. +use super::{ + contract::*, + ledger::Ledger, + matching::{MatchingEffect, MatchingOutcome}, + replay::ReplayBounds, + scalar::Posting, +}; +use serde::Serialize; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionEquity { + pub session: RiskSessionIdentity, + pub period_start: EventTime, + pub period_end: EventTime, + pub partial_start: bool, + pub partial_end: bool, + pub equity: Posting, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OccupiedInterval { + pub start: EventTime, + pub end: EventTime, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReportingFacts { + pub calendar_id: Id, + pub calendar_revision: Id, + pub trade_start: EventTime, + pub trade_end: EventTime, + pub initial_equity: Posting, + pub sampling: &'static str, + pub exposure_basis: &'static str, + pub sessions: Vec, + pub occupied_intervals: Vec, + pub occupied_ms: String, + pub elapsed_ms: String, +} + +#[derive(Debug)] +pub(super) struct Reporting { + facts: ReportingFacts, + session: RiskSessionIdentity, + period_start: EventTime, + boundaries: Vec, + next_boundary: usize, + occupied_since: Option, + failure: Option, + complete: bool, +} + +impl Reporting { + pub fn new( + initial: &RiskSessionIdentity, + boundaries: &[RiskSessionIdentity], + bounds: &ReplayBounds, + initial_equity: Posting, + ) -> Self { + // Replay has already validated/canonicalized this account calendar. + let session = boundaries + .iter() + .rev() + .find(|b| b.starts_at.get() <= bounds.trade_start.get()) + .unwrap_or(initial) + .clone(); + Self { + facts: ReportingFacts { + calendar_id: initial.calendar_id.clone(), + calendar_revision: initial.calendar_revision.clone(), + trade_start: bounds.trade_start, + trade_end: bounds.trade_end, + initial_equity, + sampling: "account-boundary-after-observations-v1", + exposure_basis: "elapsed-calendar-time", + sessions: Vec::new(), + occupied_intervals: Vec::new(), + occupied_ms: "0".into(), + // Both endpoints are safe i64 timestamps; their difference may + // exceed JS's safe integer domain but cannot overflow i64. + elapsed_ms: (bounds.trade_end.get() - bounds.trade_start.get()).to_string(), + }, + session, + period_start: bounds.trade_start, + boundaries: boundaries + .iter() + .filter(|b| b.starts_at.get() > bounds.trade_start.get()) + .cloned() + .collect(), + next_boundary: 0, + occupied_since: None, + failure: None, + complete: false, + } + } + + /// Called only after the complete equal-time Observation group. No extra + /// event enters Replay.events, and the earlier risk reset is untouched. + pub fn after_observations(&mut self, at: EventTime, ledger: &Ledger) { + if self.failure.is_some() || self.complete { + return; + } + let Some(boundary) = self.boundaries.get(self.next_boundary) else { + return; + }; + if boundary.starts_at != at { + return; + } + let next_session = boundary.clone(); + if self.sample(at, false, ledger) { + self.session = next_session; + self.period_start = at; + self.next_boundary += 1; + } + } + + fn sample(&mut self, at: EventTime, partial_end: bool, ledger: &Ledger) -> bool { + match ledger.equity() { + Ok(equity) => { + self.facts.sessions.push(SessionEquity { + session: self.session.clone(), + period_start: self.period_start, + period_end: at, + partial_start: self.period_start != self.session.starts_at, + partial_end, + equity, + }); + true + } + Err(error) => { + self.failure = Some(format!("reporting equity unavailable: {error}")); + false + } + } + } + + /// Only a committed fill can change occupancy. Query authoritative current + /// holdings once per matching outcome; never reconstruct quantities/deltas. + pub fn committed(&mut self, at: EventTime, outcome: &MatchingOutcome, ledger: &Ledger) { + if self.failure.is_some() || self.complete || outcome.replayed { + return; + } + let filled = outcome.effects.iter().any(|effect| match effect { + MatchingEffect::Risk { outcome, .. } if !outcome.replayed => outcome + .financial + .as_ref() + .filter(|financial| !financial.replayed) + .is_some_and(|financial| { + financial + .effects + .effects + .iter() + .any(|effect| matches!(effect, FinancialEffect::FillApplied { .. })) + }), + _ => false, + }); + if !filled { + return; + } + let occupied = ledger.owned_quantities().next().is_some(); + match (self.occupied_since, occupied) { + (None, true) => self.occupied_since = Some(at), + (Some(start), false) => { + self.interval(start, at); + self.occupied_since = None; + } + _ => {} + } + } + + fn interval(&mut self, start: EventTime, end: EventTime) { + let start = if start.get() < self.facts.trade_start.get() { + self.facts.trade_start + } else { + start + }; + let end = if end.get() > self.facts.trade_end.get() { + self.facts.trade_end + } else { + end + }; + if start.get() >= end.get() { + return; + } + if let Some(last) = self.facts.occupied_intervals.last_mut() { + if last.end.get() >= start.get() { + if end.get() > last.end.get() { + last.end = end; + } + return; + } + } + self.facts + .occupied_intervals + .push(OccupiedInterval { start, end }); + } + + pub fn finish(&mut self, ledger: &Ledger) { + if self.failure.is_some() || self.complete { + return; + } + if self.next_boundary != self.boundaries.len() { + self.failure = Some("reporting boundary was not sampled".into()); + return; + } + if self.period_start.get() < self.facts.trade_end.get() + && !self.sample(self.facts.trade_end, true, ledger) + { + return; + } + if let Some(start) = self.occupied_since.take() { + self.interval(start, self.facts.trade_end); + } + let occupied: i64 = self + .facts + .occupied_intervals + .iter() + .map(|interval| interval.end.get() - interval.start.get()) + .sum(); + self.facts.occupied_ms = occupied.to_string(); + self.complete = true; + } + + pub fn facts(&self) -> Result<&ReportingFacts, &str> { + if let Some(failure) = &self.failure { + Err(failure) + } else if !self.complete { + Err("reporting is incomplete") + } else { + Ok(&self.facts) + } + } +} diff --git a/apps/stock/engine/src/financial/reporting_tests.rs b/apps/stock/engine/src/financial/reporting_tests.rs new file mode 100644 index 00000000..771a0026 --- /dev/null +++ b/apps/stock/engine/src/financial/reporting_tests.rs @@ -0,0 +1,159 @@ +use super::{contract::*, ledger::Ledger, matching::*, replay::ReplayBounds, reporting::Reporting}; +use serde_json::{json, Value}; + +fn time(at: i64) -> EventTime { + at.try_into().unwrap() +} +fn ledger() -> Ledger { + Ledger::new( + serde_json::from_value(json!({ + "version":1,"sessionId":"s","accountId":"a","baseCurrency":"USD", + "reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"10000", + "riskSession":{"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0} + })) + .unwrap(), + ) + .unwrap() +} +fn initial() -> RiskSessionIdentity { + serde_json::from_value( + json!({"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}), + ) + .unwrap() +} +fn reporting(ledger: &Ledger, start: i64, end: i64) -> Reporting { + let mut initial = initial(); + initial.starts_at = time(start.min(0)); + Reporting::new( + &initial, + &[], + &ReplayBounds { + warmup_start: time(start), + trade_start: time(start), + trade_end: time(end), + }, + ledger.cash(), + ) +} +fn apply(ledger: &mut Ledger, at: i64, name: &str, body: Value) -> MatchingOutcome { + let command: EngineFinancialCommand = serde_json::from_value(json!({ + "version":1,"sessionId":"s","accountId":"a","commandId":name,"eventTime":at,"body":body, + })) + .unwrap(); + let financial = ledger.apply(&command).unwrap(); + // A reporting unit fixture wraps an actual ledger receipt, not invented deltas. + serde_json::from_value(json!({"replayed":false,"revision":1,"status":"Running","effects":[{ + "Risk":{"command":{"commandId":name,"eventTime":at,"body":{"kind":"mark","instrumentId":"X","price":"10","observedAt":at}}, + "outcome":{"replayed":false,"revision":1,"disposition":"Accepted","financial":financial, + "remaining":null,"releasedOrder":null,"resetBaseline":null}} + }]})).unwrap() +} +fn fill(ledger: &mut Ledger, at: i64, owner: &str, side: &str) -> MatchingOutcome { + let name = format!("{owner}-{side}-{at}"); + apply( + ledger, + at, + &name, + json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":name,"sequence":0}, + "orderId":name,"fillId":name,"instrumentId":"X","side":side,"quantity":"1","price":"10", + "fee":{"feeId":name,"amount":"0"}}), + ) +} + +#[test] +fn overlapping_positions_open_position_exposure_and_same_time_handoff() { + let mut ledger = ledger(); + apply( + &mut ledger, + 0, + "mark", + json!({"kind":"mark","instrumentId":"X","price":"10"}), + ); + let mut report = reporting(&ledger, 0, 50); + for (at, owner, side) in [ + (10, "A", "buy"), + (20, "B", "buy"), + (25, "A", "sell"), + (30, "B", "sell"), + (30, "A", "buy"), + (40, "A", "sell"), + (40, "B", "buy"), + ] { + let outcome = fill(&mut ledger, at, owner, side); + report.committed(time(at), &outcome, &ledger); + } + report.finish(&ledger); + let facts = report.facts().unwrap(); + assert_eq!(facts.occupied_ms, "40"); + assert_eq!(facts.elapsed_ms, "50"); + assert_eq!(facts.occupied_intervals.len(), 1); + assert_eq!(facts.occupied_intervals[0].start, time(10)); + assert_eq!(facts.occupied_intervals[0].end, time(50)); + assert!(ledger.owned_quantities().next().is_some()); +} + +#[test] +fn reporting_skips_each_nested_replayed_alias_and_zero_length_occupancy() { + for level in 0..3 { + let mut ledger = ledger(); + apply( + &mut ledger, + 0, + "mark", + json!({"kind":"mark","instrumentId":"X","price":"10"}), + ); + let mut report = reporting(&ledger, 0, 30); + let outcome = fill(&mut ledger, 10, "A", "buy"); + let mut alias = outcome.clone(); + if level == 0 { + alias.replayed = true; + } + let MatchingEffect::Risk { outcome: risk, .. } = &mut alias.effects[0] else { + panic!() + }; + if level == 1 { + risk.replayed = true; + } + if level == 2 { + risk.financial.as_mut().unwrap().replayed = true; + } + report.committed(time(0), &alias, &ledger); + report.committed(time(10), &outcome, &ledger); + let sell = fill(&mut ledger, 10, "A", "sell"); + report.committed(time(10), &sell, &ledger); + report.finish(&ledger); + assert!(report.facts().unwrap().occupied_intervals.is_empty()); + assert_eq!(report.facts().unwrap().occupied_ms, "0"); + } +} + +#[test] +fn reporting_failure_retains_financial_state_and_cannot_return_success() { + let mut ledger = ledger(); + let mut report = reporting(&ledger, 0, 20); + fill(&mut ledger, 10, "A", "buy"); // No mark: ledger equity is explicitly unavailable. + let checkpoint = ledger.checkpoint(); + report.finish(&ledger); + assert!(report.facts().unwrap_err().contains("equity unavailable")); + assert_eq!(ledger.checkpoint(), checkpoint); + apply( + &mut ledger, + 15, + "mark", + json!({"kind":"mark","instrumentId":"X","price":"10"}), + ); + report.finish(&ledger); // A failed report cannot silently become successful later. + assert!(report.facts().is_err()); +} + +#[test] +fn duration_strings_cover_the_entire_safe_timestamp_domain_without_rounding() { + let ledger = ledger(); + let mut report = reporting(&ledger, -9_007_199_254_740_991, 9_007_199_254_740_990); + assert!(report.facts().is_err()); + report.finish(&ledger); + let facts = report.facts().unwrap(); + assert_eq!(facts.elapsed_ms, "18014398509481981"); + assert_eq!(facts.occupied_ms, "0"); + assert!(!facts.sessions[0].partial_start && facts.sessions[0].partial_end); +} diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index 223f98fa..c6b03e02 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -2,6 +2,7 @@ import { fork, type ChildProcess } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { parseReplayProjectionResult, + parseReplayReportResult, parseReplayResult, replayConfigSchema, replayIdentitySchema, @@ -85,9 +86,11 @@ export class NativeBacktestWorker { if (expectedReplay) { try { const parse = - expectedReplay.format === 'projection' - ? parseReplayProjectionResult - : parseReplayResult; + expectedReplay.format === 'report' + ? parseReplayReportResult + : expectedReplay.format === 'projection' + ? parseReplayProjectionResult + : parseReplayResult; parse(message.result, expectedReplay.identity, expectedReplay.policy); } catch (error) { terminate(error instanceof Error ? error : new Error(String(error))); diff --git a/apps/stock/orchestrator/src/backtest/canonical-result.ts b/apps/stock/orchestrator/src/backtest/canonical-result.ts new file mode 100644 index 00000000..4e50d271 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/canonical-result.ts @@ -0,0 +1,195 @@ +import { z } from 'zod'; +import { + dayMs, + drawdownAnalysis, + nullable, + ratio, + returnStatistics, +} from '@stock-bot/calculations/analytics'; +import { cagr, simpleReturn } from '@stock-bot/calculations/returns'; +import type { + CanonicalBacktestAnalytics, + CanonicalMetrics, + CanonicalMetricsInput, + CanonicalMetricUnavailableReason, + CanonicalSessionReturn, +} from '@stock-bot/types'; +import type { ReplayReportResult } from '../contracts/native-replay'; + +const metricsInput = z + .object({ + version: z.literal(1), + periodsPerYear: z.number().finite().positive(), + annualRiskFreeRate: z.number().finite().nullable(), + benchmark: z.null(), + }) + .strict(); + +export interface CanonicalBacktestReport { + /** Exact validated Rust facts; never converted through the legacy DTO. */ + financial: ReplayReportResult; + analytics: CanonicalBacktestAnalytics; +} + +/** Consume a validated report from the native protocol parser. Financial facts + * stay untouched; only statistical reporting converts decimal equity to numbers. + * Persistence/public-result migration belongs to the separately gated R05 path. */ +export function buildCanonicalBacktestReport( + financial: ReplayReportResult, + input: CanonicalMetricsInput +): CanonicalBacktestReport { + const policy = metricsInput.parse(input); + const reporting = financial.reporting; + const initial = Number(reporting.initialEquity); + const terminal = Number(financial.projection.valuation.equity); + const elapsedMs = Number(reporting.elapsedMs); + let previous = initial; + const sessionReturns: CanonicalSessionReturn[] = reporting.sessions.map(session => { + const current = Number(session.equity); + const value = previous > 0 ? nullable(simpleReturn(previous, current)) : null; + const reason = + value === null + ? previous <= 0 + ? ('nonpositive-baseline' as const) + : ('nonfinite-result' as const) + : undefined; + previous = current; + return { + sessionId: session.session.sessionId, + periodStart: session.periodStart, + periodEnd: session.periodEnd, + partialStart: session.partialStart, + partialEnd: session.partialEnd, + value, + eligible: !session.partialStart && !session.partialEnd && value !== null, + ...(reason ? { reason } : {}), + }; + }); + const complete = sessionReturns.filter(session => !session.partialStart && !session.partialEnd); + // One undefined complete return invalidates this statistical sequence. A later + // positive baseline must not silently turn it into a shorter, different sample. + const periodicReturns = complete.every( + (session): session is CanonicalSessionReturn & { value: number } => session.value !== null + ) + ? complete.map(session => session.value) + : null; + const statistics = + periodicReturns === null + ? null + : returnStatistics(periodicReturns, policy.annualRiskFreeRate, policy.periodsPerYear); + const points = [ + { timestamp: reporting.tradeStart, value: initial }, + ...reporting.sessions.map(session => ({ + timestamp: session.periodEnd, + value: Number(session.equity), + })), + ]; + const metrics: CanonicalMetrics = { + totalReturn: initial > 0 ? nullable(simpleReturn(initial, terminal)) : null, + cagr: initial > 0 ? cagr(initial, terminal, elapsedMs / dayMs / 365) : null, + maxDrawdown: initial > 0 ? drawdownAnalysis(points, initial).maxDrawdown : null, + exposureTime: ratio(Number(reporting.occupiedMs), elapsedMs), + volatility: statistics?.volatility ?? null, + downsideDeviation: statistics?.downsideDeviation ?? null, + sharpeRatio: statistics?.sharpeRatio ?? null, + sortinoRatio: statistics?.sortinoRatio ?? null, + var95: statistics?.var95 ?? null, + cvar95: statistics?.cvar95 ?? null, + var99: statistics?.var99 ?? null, + alpha: null, + beta: null, + informationRatio: null, + roundTripCount: null, + winRate: null, + profitFactor: null, + avgWin: null, + avgLoss: null, + }; + const unavailable: CanonicalBacktestAnalytics['unavailable'] = { + alpha: 'missing-benchmark', + beta: 'missing-benchmark', + informationRatio: 'missing-benchmark', + roundTripCount: 'unsupported-round-trips', + winRate: 'unsupported-round-trips', + profitFactor: 'unsupported-round-trips', + avgWin: 'unsupported-round-trips', + avgLoss: 'unsupported-round-trips', + }; + if (metrics.totalReturn === null) { + unavailable.totalReturn = initial <= 0 ? 'nonpositive-baseline' : 'nonfinite-result'; + } + if (metrics.maxDrawdown === null) { + unavailable.maxDrawdown = 'nonpositive-baseline'; + } + if (metrics.exposureTime === null) { + unavailable.exposureTime = elapsedMs === 0 ? 'zero-duration' : 'nonfinite-result'; + } + if (metrics.cagr === null) { + unavailable.cagr = + initial <= 0 + ? 'nonpositive-baseline' + : elapsedMs === 0 + ? 'zero-duration' + : terminal < 0 + ? 'negative-terminal-equity' + : 'nonfinite-result'; + } + const minimumPeriods = { + volatility: 2, + downsideDeviation: 2, + sharpeRatio: 2, + sortinoRatio: 2, + var95: 20, + cvar95: 20, + var99: 100, + }; + for (const key of Object.keys(minimumPeriods) as (keyof typeof minimumPeriods)[]) { + if (metrics[key] !== null) { + continue; + } + let reason: CanonicalMetricUnavailableReason = 'nonfinite-result'; + if (periodicReturns === null) { + reason = 'undefined-period-return'; + } else if ( + ['downsideDeviation', 'sharpeRatio', 'sortinoRatio'].includes(key) && + policy.annualRiskFreeRate === null + ) { + reason = 'missing-risk-free'; + } else if (periodicReturns.length < minimumPeriods[key]) { + reason = 'insufficient-periods'; + } else if (key === 'sharpeRatio' && statistics?.volatility === 0) { + reason = 'zero-variance'; + } else if (key === 'sortinoRatio' && statistics?.downsideDeviation === 0) { + reason = 'zero-downside-deviation'; + } + unavailable[key] = reason; + } + return { + financial, + analytics: { + version: 1, + policy: { + ...policy, + calendarId: reporting.calendarId, + calendarRevision: reporting.calendarRevision, + sampling: reporting.sampling, + marks: 'last-available-no-per-session-freshness-certification', + returnUnit: 'fraction', + variance: 'sample-n-minus-one', + riskFreeConversion: 'annual-rate-divided-by-periods-per-year', + downside: 'full-series-rms-relative-to-risk-free', + partialPeriods: 'visible-excluded-from-periodic-statistics', + drawdown: 'session-end-and-terminal-sampled', + exposureBasis: reporting.exposureBasis, + cagrBasis: 'elapsed-calendar-days-365', + zeroTerminalCagr: 'negative-one-for-positive-elapsed-time', + }, + sessionReturns, + completePeriodCount: complete.length, + periodicSampleCount: periodicReturns?.length ?? 0, + fillCount: financial.projection.fills.length, + metrics, + unavailable, + }, + }; +} diff --git a/apps/stock/orchestrator/src/backtest/native-replay.ts b/apps/stock/orchestrator/src/backtest/native-replay.ts index 1fb6c7c7..e9c64962 100644 --- a/apps/stock/orchestrator/src/backtest/native-replay.ts +++ b/apps/stock/orchestrator/src/backtest/native-replay.ts @@ -8,6 +8,7 @@ import { } from '@stock-bot/types'; import { parseReplayProjectionValue, + parseReplayReportValue, parseReplayResultValue, replayConfigSchema, replayTraceSchema, @@ -20,6 +21,7 @@ import { type ReplayIdentity, type ReplayOutput, type ReplayProjectionResult, + type ReplayReportResult, type ReplayResult, type ReplayResultFormat, type ReplayStep, @@ -33,6 +35,7 @@ export type { ReplayStep, ReplayResult, ReplayProjectionResult, + ReplayReportResult, ReplayOutput, ReplayResultFormat, DecisionContext, @@ -197,6 +200,13 @@ export class NativeReplaySession { input => parseReplayProjectionValue(input, this.identity) ); } + report(): ReplayReportResult { + const identity = JSON.stringify(this.identity); + return this.finish( + () => this.native.report(identity), + input => parseReplayReportValue(input, this.identity) + ); + } private finish(native: () => string, validate: (input: unknown) => T): T { let start = performance.now(); const raw = native(); @@ -243,6 +253,11 @@ interface ReplayOptions { resultFormat?: ReplayResultFormat; } /* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */ +export function runReplayConformance( + session: NativeReplaySession, + decide: Decide, + options: ReplayOptions & { resultFormat: 'report' } +): { result: ReplayReportResult; metrics: ReplayMetrics }; export function runReplayConformance( session: NativeReplaySession, decide: Decide, @@ -301,7 +316,12 @@ export function runReplayConformance( throw new Error(step.step.diagnostic); case 'complete': { const start = performance.now(), - result = options.resultFormat === 'projection' ? session.project() : session.finalize(); + result = + options.resultFormat === 'report' + ? session.report() + : options.resultFormat === 'projection' + ? session.project() + : session.finalize(); metrics.finalizeMs = performance.now() - start; metrics.finalizeNativeMs = session.finalization.nativeMs; metrics.finalizeDecodeMs = session.finalization.decodeMs; @@ -359,6 +379,10 @@ export function runReplayConformance( /** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */ /* eslint-disable no-redeclare -- TypeScript overloads narrow the selected result format. */ +export function executeReplayTrace( + input: ReplayTraceRequest & { resultFormat: 'report' }, + onProgress?: (step: ReplayStep) => void +): { result: ReplayReportResult; metrics: ReplayMetrics }; export function executeReplayTrace( input: ReplayTraceRequest & { resultFormat: 'projection' }, onProgress?: (step: ReplayStep) => void diff --git a/apps/stock/orchestrator/src/contracts/native-replay.ts b/apps/stock/orchestrator/src/contracts/native-replay.ts index a6c01216..652d57f9 100644 --- a/apps/stock/orchestrator/src/contracts/native-replay.ts +++ b/apps/stock/orchestrator/src/contracts/native-replay.ts @@ -239,9 +239,44 @@ const projectionResultSchema = resultSchema }) .strict(); export type ReplayProjectionResult = z.infer; -export const replayResultFormatSchema = z.enum(['trace', 'projection']); +export const replayReportingSchema = z + .object({ + calendarId: id, + calendarRevision: id, + tradeStart: time, + tradeEnd: time, + initialEquity: nonnegative, + sampling: z.literal('account-boundary-after-observations-v1'), + exposureBasis: z.literal('elapsed-calendar-time'), + sessions: z.array( + z + .object({ + session: riskSession, + periodStart: time, + periodEnd: time, + partialStart: z.boolean(), + partialEnd: z.boolean(), + equity: nonnegative, + }) + .strict() + ), + occupiedIntervals: z.array(z.object({ start: time, end: time }).strict()), + occupiedMs: z.string().regex(/^(0|[1-9][0-9]*)$/), + elapsedMs: z.string().regex(/^(0|[1-9][0-9]*)$/), + }) + .strict(); +const reportResultSchema = projectionResultSchema + .extend({ + format: z.literal('report'), + reportingVersion: z.literal(1), + reporting: replayReportingSchema, + }) + .strict(); +export type ReplayReporting = z.infer; +export type ReplayReportResult = z.infer; +export const replayResultFormatSchema = z.enum(['trace', 'projection', 'report']); export type ReplayResultFormat = z.infer; -export type ReplayOutput = ReplayResult | ReplayProjectionResult; +export type ReplayOutput = ReplayResult | ReplayProjectionResult | ReplayReportResult; export type DecisionContext = Extract; export type PublishedObservation = z.infer; @@ -301,13 +336,16 @@ export function parseReplayProjectionValue( ): ReplayProjectionResult { const result = projectionResultSchema.parse(input); checkResultIdentity(result, identity, expectedPolicy); + checkProjection(result); + return result; +} +function checkProjection(result: ReplayProjectionResult | ReplayReportResult): void { if ( result.projection.valuation.cash !== result.view.portfolio.cash || result.projection.valuation.equity !== result.view.equity ) { throw new Error('Native replay projection does not match terminal view'); } - return result; } export function parseReplayProjectionResult( input: string, @@ -317,6 +355,101 @@ export function parseReplayProjectionResult( return parseReplayProjectionValue(JSON.parse(input), identity, expectedPolicy); } +export function parseReplayReportValue( + input: unknown, + identity: ReplayIdentity, + expectedPolicy?: ReplayConfig +): ReplayReportResult { + const result = reportResultSchema.parse(input); + checkResultIdentity(result, identity, expectedPolicy); + checkProjection(result); + const report = result.reporting; + const bounds = z.object({ tradeStart: time, tradeEnd: time }).parse(result.manifest.bounds); + const initial = result.policy.matching.risk.ledger; + if ( + report.tradeStart !== bounds.tradeStart || + report.tradeEnd !== bounds.tradeEnd || + report.tradeStart >= report.tradeEnd || + report.calendarId !== initial.riskSession.calendarId || + report.calendarRevision !== initial.riskSession.calendarRevision || + report.initialEquity !== initial.initialCapital || + report.sessions.at(-1)?.equity !== result.view.equity + ) { + throw new Error('Native replay reporting identity or terminal value mismatch'); + } + // Check calendar partition/labels, not equity arithmetic or financial accounting. + const boundaries = [...result.policy.risk_boundaries].sort((a, b) => a.startsAt - b.startsAt); + let session = initial.riskSession; + let start = report.tradeStart, + index = 0; + for (const boundary of boundaries) { + if (boundary.startsAt <= report.tradeStart) { + session = boundary; + continue; + } + if (boundary.startsAt > report.tradeEnd) { + break; + } + const actual = report.sessions[index++]; + if ( + !actual || + JSON.stringify(actual.session) !== JSON.stringify(session) || + actual.periodStart !== start || + actual.periodEnd !== boundary.startsAt || + actual.partialStart !== (start !== session.startsAt) || + actual.partialEnd + ) { + throw new Error('Native replay reporting session partition mismatch'); + } + start = boundary.startsAt; + session = boundary; + } + if (start < report.tradeEnd) { + const actual = report.sessions[index++]; + if ( + !actual || + JSON.stringify(actual.session) !== JSON.stringify(session) || + actual.periodStart !== start || + actual.periodEnd !== report.tradeEnd || + actual.partialStart !== (start !== session.startsAt) || + !actual.partialEnd + ) { + throw new Error('Native replay reporting final session mismatch'); + } + } + if (index !== report.sessions.length) { + throw new Error('Native replay reporting has extra sessions'); + } + let occupied = 0n, + previousEnd: number | undefined; + for (const interval of report.occupiedIntervals) { + if ( + interval.start < report.tradeStart || + interval.end > report.tradeEnd || + interval.start >= interval.end || + (previousEnd !== undefined && interval.start <= previousEnd) + ) { + throw new Error('Native replay reporting intervals are not a clipped union'); + } + occupied += BigInt(interval.end) - BigInt(interval.start); + previousEnd = interval.end; + } + if ( + report.occupiedMs !== String(occupied) || + report.elapsedMs !== String(BigInt(report.tradeEnd) - BigInt(report.tradeStart)) + ) { + throw new Error('Native replay reporting duration mismatch'); + } + return result; +} +export function parseReplayReportResult( + input: string, + identity: ReplayIdentity, + expectedPolicy?: ReplayConfig +): ReplayReportResult { + return parseReplayReportValue(JSON.parse(input), identity, expectedPolicy); +} + export const replayTraceSchema = z .object({ type: z.literal('runReplayTrace'), diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index a4c4a303..d984f9ae 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,6 +1,6 @@ # Revised development roadmap -Baseline `b7aeca4` · execution 2026-10-23 · **F09/P07 committed; F08 in progress** +Baseline `b7aeca4` · execution 2026-10-23 · **F09/P07 committed; F08 validated, uncommitted** Authorization update: the owner accepted the validated performance work and requested commit plus backlog continuation. F09/P07 are committed as `e3bd722`; F08 historical reporting is now authorized under ADR-002/003/004. No other ADR or multi-asset mark policy is approved. New implementation commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope. @@ -317,6 +317,29 @@ Account-session samples follow all equal-time observations without changing the F08 adds a canonical analytics DTO beside the existing result contract. It does not fabricate the legacy DTO's per-position mark/average/P&L fields or infer round trips from fills. R05 retains persisted/public-result migration and default cutover. Existing readers/UI remain compatibility gates. No new financial policy, cache/DSL, journal deletion or unrelated per-step performance change is included. +**Validated handoff:** F08 is `review` / `validated_uncommitted`. Root integrated all 22 owner files with exact independently reviewed hashes and added a real native → worker → analytics composition test. The planning commit is `1e16445`; no F08 implementation commit has been made. + +- Rust records account-session equity after equal-time observations and unions actual occupied intervals, including open positions at termination. Restore reconstructs the same facts without changing financial event IDs, checkpoints or existing trace/projection output. +- Native `report()` and the existing worker transport expose the versioned facts. The additive TypeScript adapter reuses reviewed calculations with explicit annualization/risk-free policy, partial-period exclusion and nullable unsupported metrics. Shared calculations retain old defaults for old callers; exactly constant returns and zero terminal-equity CAGR now have pinned edge-case tests. +- Repository build, typecheck, contract, audit and lint gates passed, with 72 tooling, 43 utility, 44 calculation and 144 Rust tests. Four existing manual Rust benchmarks remain ignored. The initial integration run exposed missing explicit hold decisions in the new composition fixture; after that test-only correction, **375 integration tests / 3,345 assertions passed**. Strict test TypeScript, scoped ESLint/Prettier/rustfmt and diff checks passed. Disposable PostgreSQL/Redis recovery suites passed **58 tests / 345 assertions** before and after integration. The release addon passed **39 focused native/worker/analytics tests / 703 assertions**. Counts overlap; browser/Python boundaries did not change and those suites were not rerun. + +Release measurements used six synthetic workloads with **10,000 total bars**, one asset/owner or ten assets/two owners, and no-trade/sparse/turnover strategies. The first candidate appeared 33–44% slower than the early baseline, including unchanged TypeScript callback/JSON phases. Shared host load varied materially. A contemporaneous rerun of the exact unchanged F09 release reproduced that slowdown; 128 relevant control source files match `e3bd722`. All complete result and financial hashes agree. Retain both sets of evidence; this is not a speedup claim. + +| Workload | Early F09 median | Contemporaneous F09 control | F08 median | F08 vs control | +| --- | ---: | ---: | ---: | ---: | +| No trade, 1 asset / 1 owner | 722 ms | 1,050 ms | 1,037 ms | −1.2% | +| No trade, 10 assets / 2 owners | 301 ms | 422 ms | 413 ms | −2.2% | +| Sparse, 1 asset / 1 owner | 788 ms | 1,137 ms | 1,125 ms | −1.0% | +| Sparse, 10 assets / 2 owners | 425 ms | 589 ms | 582 ms | −1.3% | +| Turnover, 1 asset / 1 owner | 1,425 ms | 1,994 ms | 2,009 ms | +0.7% | +| Turnover, 10 assets / 2 owners | 1,820 ms | 2,432 ms | 2,426 ms | −0.3% | + +Each median has four fresh-session samples across two processes. A separate counterbalanced comparison of projection/report output passed all **48 sessions**, exact repeated report/analytics hashes and an independent integer-cent oracle. Removing reporting fields and normalizing the format discriminator to `projection` yields the identical complete projection. Report finalization medians were 0.24–6.77 ms higher; analytics took 0.50–1.28 ms. These fixtures have only one partial account period: they measure export/occupancy and minimal analytics, not long histories of session statistics, durable research throughput or empty NAPI cost. There is no demonstrated material replay regression on these workloads, and no stable-host SLA is claimed. + +Raw samples, source/artifact hashes, commands and review evidence are in `manifest.json` → `thirteenth_wave_validation`, with retained files under `/tmp/stock-bot-wave13.KfvceG/`. Only the two exact disposable test containers were stopped; development services were untouched. Source worktrees and logs remain. + +Limits: sampled drawdown is not intraday maximum; marks are last available without per-session freshness certification; benchmark-dependent and round-trip statistics remain null with reasons. Sequential equal-time marks can still latch intermediate risk halts. R05 retains its owner policy gate and public/persisted result cutover. **Next after acceptance: S01 stateful TypeScript strategy decisions**, requiring ADR-005 approval; R01/R11 require ADR-006. No pending decision, default cutover, push, PR or trading operation was implicitly approved. + ## Deferred and rejected Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 2a7a891e..608b5e34 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First twelve waves committed; F08 in progress.** F09/P07 were accepted as `e3bd722`. F08 adds account-session equity, occupied-time exposure and explicit statistical policies on the same financial core. Consult manifest execution_scope and [current wave](../ROADMAP.md#thirteenth-wave-execution--2026-10-23). ADR-002/003/004 are approved; other policies/default cutovers remain gated. +**First twelve waves committed; F08 validated and awaiting acceptance.** F09/P07 were accepted as `e3bd722`; `1e16445` records their completion and the F08 contract. F08 adds account-session equity, occupied-time exposure and explicit statistical policies on the same financial core. Consult manifest execution_scope and [current wave](../ROADMAP.md#thirteenth-wave-execution--2026-10-23). ADR-002/003/004 are approved; other policies/default cutovers remain gated. ## One source of truth @@ -36,7 +36,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / done | F04, ADR-003 | F06 | Rust execution semantics / L | | [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / done | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M | | [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / done | F06, C02, ADR-004 | — | Rust/TypeScript integration / M | -| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / in_progress | F06, F09, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M | +| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / review | F06, F09, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M | | [F09 Return compact canonical replay projections](tasks/F09.md) | P1 / done | F07, ADR-002, ADR-003, ADR-004 | — | Rust/TypeScript financial integration / M | ### E3 — Point-in-time datasets and features @@ -117,4 +117,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. -The first eleven waves are independently reviewed, validated and committed. Current authorization covers **F09 compact projections and P07 profiling** only. P07 baseline files can progress in parallel; paired projection measurements consume the accepted F09 contract afterward. F08 adds historical sampling/statistics next, without reconstructing accounting in TS. S01 needs ADR-005 and R01 needs ADR-006. The unresolved multi-asset mark-policy gate still blocks default activation. No new commit, push, PR or trading operation is authorized. +The first twelve waves are committed. **F08 is independently reviewed and validated, with new implementation changes uncommitted.** Its reporting facts and statistics preserve authoritative Rust financial output; R05 retains persistence and public-result migration. Next, S01 needs ADR-005 approval; R01/R11 need ADR-006. The unresolved multi-asset mark-policy gate still blocks default activation. No further task, new commit, push, PR or trading operation is included in this continuation. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index e9513fdf..b0a202a0 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,8 +1,8 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.29", + "plan_revision": "2026-10-23.30", "repository_base": "b7aeca4", - "plan_status": "thirteenth_wave_in_progress", + "plan_status": "thirteenth_wave_in_review", "execution_authorized": true, "execution_scope": { "authorized_by": "User: lets commit and continue with the backlog (2026-10-23). Accepted F09/P07 commit and authorizes F08 canonical historical reporting under approved ADR002/003/004; no default cutover or new financial policy.", @@ -650,7 +650,7 @@ "epic": "E2", "priority": "P1", "severity": "High", - "status": "in_progress", + "status": "review", "dependencies": [ "F06", "F09" @@ -682,7 +682,7 @@ "release_gates": [], "worktree": "/tmp/stock-bot-wave13.KfvceG/f08", "integration_base": "e3bd722e31a4e14519df543d87affd90a8103fa2", - "integration_state": "isolated_implementation", + "integration_state": "validated_uncommitted", "implementation_slices": [ { "owner": "/root/f08_contract_review", @@ -697,7 +697,9 @@ "branch": "wave13/f08-analytics" } ], - "review_notes": "Root pinned reporting conventions in F08 Execution contract. Preserve financial event IDs/checkpoints/trace/projection outputs. Additive canonical analytics contract; incompatible legacy DTO/persistence/public-result migration remains R05. No default cutover." + "review_notes": "Independent reviews accepted native/reporting and analytics slices. 22 owner files integrated with exact hashes plus root native/worker/analytics composition tests. Repository gates, disposable recovery and release comparisons pass; shared-host drift checked against unchanged release control. Financial event IDs/checkpoints/trace/projection and legacy paths retained. See thirteenth_wave_validation; R05 owns persisted/public-result cutover.", + "reviewed_by": ["/root/wave12_review", "/root"], + "verification_reference": "ROADMAP.md#thirteenth-wave-execution--2026-10-23" }, { "id": "F09", @@ -4925,5 +4927,280 @@ "Reporting conventions pinned in F08 Execution contract after independent Rust/quant design inspection. Separate accumulator; existing financial events/checkpoints/config/outputs retained; account-session reporting and elapsed occupancy are explicit.", "Two isolated source owners: native/reporting wire and disjoint shared analytics/statistics adapter. Exact accepted schema is handed off before consumer integration. Independent reviewer is read-only.", "Legacy positions and round-trip DTOs cannot truthfully represent the new facts without further work. F08 publishes an additive canonical analytics DTO; R05 retains persisted/public-result/default cutover with existing approval gates." - ] + ], + "thirteenth_wave_validation": { + "state": "validated_uncommitted", + "work_root": "/tmp/stock-bot-wave13.KfvceG", + "committed_before_implementation": [ + "e3bd722e31a4e14519df543d87affd90a8103fa2", + "1e164450c3f7a16c1838b3318842f49a5ff3cf28" + ], + "scope": "F08 only. Additive reporting/analytics; financial events/checkpoints/trace/projection and active legacy/web/paper paths unchanged. R05 owns persisted/public-result cutover.", + "source_integration": { + "reviewed_owner_files": 22, + "all_owner_hashes_match": true, + "root_additions": [ + "test/integration/canonical-native-report.test.ts", + "libs/calculations/README.md" + ], + "source_archive": "/tmp/stock-bot-wave13.KfvceG/integrated-source.tar", + "source_archive_sha256": "1b72060dd11f4f7577d5078798188b0e024a34c951d316b3a29cfde193eb3a04", + "measured_source": { + "commit": "1e164450c3f7a16c1838b3318842f49a5ff3cf28", + "dirty": true, + "contentSha256": "4f60ad86bf2ef9afbc2630563d3ae2c8c5a54e60f4a57c82de798edc1a497a00", + "files": 1167 + }, + "owner_hashes_file": "/tmp/stock-bot-wave13.KfvceG/f08-sources.sha256 and /tmp/stock-bot-wave13.KfvceG/analytics-final.sha256" + }, + "gates": { + "repository": { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave13.KfvceG/integration-check.log", + "outcome": "Build/typecheck/contracts/audit/lint passed; 72 tooling, 43 utility, 44 calculation and 144 Rust tests passed (4 existing manual benchmarks ignored). Initial integration failed only new composition fixtures missing explicit hold decisions; fixed test only. Required integration rerun below passed; no production changes after passing gates." + }, + "integration": { + "command": "bun run test:integration", + "log": "/tmp/stock-bot-wave13.KfvceG/integration-tests-final.log", + "passed": 375, + "assertions": 3345 + }, + "strict_test_types": { + "command": "bunx tsc --project /tmp/stock-bot-wave13.KfvceG/tsconfig.integration.json --noEmit", + "log": "/tmp/stock-bot-wave13.KfvceG/integration-extra-types-final.log", + "passed": true + }, + "disposable_recovery": { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32809/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32810/15 bun run test:postgres", + "baseline_log": "/tmp/stock-bot-wave13.KfvceG/baseline-postgres.log", + "integrated_log": "/tmp/stock-bot-wave13.KfvceG/integration-postgres.log", + "passed_each": 58, + "assertions_each": 345 + }, + "release_focused": { + "command": "bun test test/integration/native-replay.test.ts test/integration/native-replay-projection.test.ts test/integration/native-replay-report.test.ts test/integration/canonical-result.test.ts test/integration/canonical-native-report.test.ts scripts/test/native-bindings.test.ts", + "log": "/tmp/stock-bot-wave13.KfvceG/integration-release-focused.log", + "passed": 39, + "assertions": 703 + }, + "formatting": "Scoped test ESLint with --no-ignore --max-warnings 0; scoped Prettier and Rust rustfmt; git diff --check passed.", + "review": "Independent frozen native/wire and analytics review; real native/worker/analytics composition reviewed after corrected exact-trace fixtures. No blockers. Focused counts overlap full suites.", + "not_run": "Browser/Python unchanged; no browser or Python rerun. No default cutover, paper account migration or live operation." + }, + "native": { + "release_sha256": "6fe9dae546b4fc1d50b064b2ad50b0a3d08a0208ede3c568bf0f95e549c57b9e", + "artifact_matches": "apps/stock/engine/dist/engine.node == target/release/libengine.so", + "generated_types_sha256": "4ab02314df3b64ae698942d5ba69260430f4488dc8ad64d1ef825d86db71da5d" + }, + "performance": { + "methodology": "Release; six workloads of 10000 TOTAL bars, one asset/owner or ten assets/two owners, none/sparse/turnover; two fresh processes x two fresh sessions each. Shared host; no timing assertions.", + "projection_command": "bun run scripts/benchmark-research.ts --session --measure --profile=all --format=projection --bars=10000", + "raw_files": { + "baseline": { + "path": "/tmp/stock-bot-wave13.KfvceG/baseline-10k-projection.json", + "sha256": "3fd571b271d7ebdacd078315ab8c7102bb4d26edbeb31d9d15ce97e0b1efa6dc" + }, + "candidate": { + "path": "/tmp/stock-bot-wave13.KfvceG/candidate-10k-projection.json", + "sha256": "e122cdd57d9126eeecf5d85203485dfaded47cbede24a61ce726e0cc8c548b2d" + }, + "control": { + "path": "/tmp/stock-bot-wave13.KfvceG/control-10k-projection.json", + "sha256": "99940d4dc6debf22e98c1cda45d79f7ae3bfad4890625b22c6f490ad5fd243d4" + }, + "comparison": { + "path": "/tmp/stock-bot-wave13.KfvceG/projection-comparison.json", + "sha256": "b11ae6348eaf944c7ec0b24abb65d0c931654e572bfa1c831c2fb2414ea3d158" + } + }, + "baseline_addon": "d98308d0af80c225f2ee631d5e68065fa762073619a8b5cf6f3681ba0f1d5dd6", + "control_source": { + "commit": "19e9dad68be9a06d1e9cd86cc27112c5dc8a4aa2", + "dirty": true, + "contentSha256": "8c181e664dfcd14951da1730918efd7817cc64c24409d12a1dbfbc65a4f3cd68", + "files": 1156, + "scope": "Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded." + }, + "projection_rows": [ + [ + "none", + 1, + 1, + 722.1379744999999, + 1036.9407385, + 1049.7488, + -1.2201072770933519, + "ba38c860ec1ea215118f3cee4ffbb214d4d22c00e6b5f59fcc041570e6595d39" + ], + [ + "none", + 10, + 2, + 301.1164395, + 412.87483849999995, + 422.0579295, + -2.1757892360603215, + "c9d2f8c913394fa37b3a4e057567ffa1463413ec5dbcda9c2c26109078b27103" + ], + [ + "sparse", + 1, + 1, + 788.4738159999999, + 1125.431942, + 1136.793305, + -0.9994220541261867, + "7bba2bd2b3183d3c73d7d0e52e8e9eefd995704d5b3ad3b19d1a0467ff07ac0a" + ], + [ + "sparse", + 10, + 2, + 425.1541205, + 581.5226849999999, + 589.4312225, + -1.3417235460410404, + "16d8bc7f63fcfbbb17a2ec949959e2976332c90a3b66f88764434bd74a1f870a" + ], + [ + "turnover", + 1, + 1, + 1425.262843, + 2008.9278365000002, + 1994.4425904999998, + 0.7262804188497007, + "84449a90550ae61b1ed7ac038a21420ed0347f7e9130d84fe960ca2d2dc7590c" + ], + [ + "turnover", + 10, + 2, + 1820.0325200000002, + 2425.662255, + 2432.1380289999997, + -0.2662584903810772, + "aa8405f705705c9153b18b00965ddca11271a3a2e9bf61787985a68cb8df620f" + ] + ], + "interpretation": "Initial candidate was 33-44% slower than early baseline, including unchanged TS callback/JSON phases. Host load varied 9-26. Contemporaneous unchanged exact F09 addon reproduced slowdown; 128 relevant source/lock files verified equal e3bd722. Candidate/control -2.18% to +0.73%; no material regression demonstrated, no speedup or SLA claim. All complete result/economic hashes identical; retain unfavorable initial samples.", + "report_comparison": { + "command": "bun run /tmp/stock-bot-wave13.KfvceG/report-benchmark.ts", + "harness": { + "path": "/tmp/stock-bot-wave13.KfvceG/report-benchmark.ts", + "sha256": "d37f63aadd9b1849a57347c27991027e31fd03121edb3c7d6fb40575af2d00a5" + }, + "smoke": "--smoke passed all tiny 8/16-total-bar pairs", + "path": "/tmp/stock-bot-wave13.KfvceG/report-comparison.json", + "sha256": "3969ca227d46655933395a744bd16a95cf6a90ca28dfe27556c6c2d66169524b", + "trials": 48, + "rows": [ + [ + "none", + 1, + 1, + 1038.244792, + 1038.0855645000001, + 0.7150815000001103, + 0.9550145000000612, + 0.5035165000000461, + 5414, + 5972 + ], + [ + "none", + 10, + 2, + 419.2966825, + 415.5477985, + 0.6127834999999777, + 1.0950445000000286, + 0.638200500000039, + 9198, + 9755 + ], + [ + "sparse", + 1, + 1, + 1140.11128, + 1122.99876, + 0.9735344999999143, + 1.2432044999999334, + 1.2845025000000305, + 7480, + 8090 + ], + [ + "sparse", + 10, + 2, + 579.425198, + 585.6239385000001, + 1.435258000000033, + 1.9801919999999882, + 0.5092425000000276, + 50387, + 50995 + ], + [ + "turnover", + 1, + 1, + 1965.9803270000002, + 2002.67703, + 197.7599379999998, + 201.9273004999999, + 0.6505395000001499, + 9784124, + 10004689 + ], + [ + "turnover", + 10, + 2, + 2466.477757, + 2465.8275665, + 431.99900449999996, + 438.7678484999997, + 0.8527414999998655, + 19408576, + 19431138 + ] + ], + "validation": "Counterbalanced format order; removing reporting fields and normalizing format to projection yields the identical complete projection, including valuation/all fill fields; matches initial baseline. Repeated full report/analytics hashes and integer-cent oracle pass. Independent final audit verified recorded raw/harness hashes, all 48 trials, medians and limitations.", + "scope": "Both formats collect reporting. Additional export median 0.24-6.77ms; adapter 0.50-1.28ms. Fixture has one partial session, zero complete periodic samples; not long-session-history statistics, storage/queue throughput, arbitrary strategies or pure NAPI costs.", + "rows_columns": [ + "profile", + "assets", + "owners", + "projection_run_ms", + "report_run_ms", + "projection_finalize_ms", + "report_finalize_ms", + "analytics_ms", + "projection_bytes", + "report_bytes" + ] + }, + "projection_rows_columns": [ + "profile", + "assets", + "owners", + "initial_baseline_ms", + "candidate_ms", + "contemporaneous_control_ms", + "candidate_vs_control_percent", + "full_result_hash" + ] + }, + "limitations": [ + "Session-end/terminal sampled drawdown, not intraday maximum; partial periods visible/excluded from periodic ratios.", + "Marks are last available; per-session freshness not certified. Sequential equal-time risk halt limitation unchanged; R05 owner policy gate unresolved.", + "Benchmark-dependent and round-trip metrics unsupported/null with reasons. Fills are not round trips; no invented legacy position financial fields.", + "Legacy financial paths/results/UI remain active until separately gated migration. No DSL/cache/journal deletion or unrelated hot-loop rewrite." + ], + "cleanup": "Stopped only exact --rm fixture containers a4edf7d7b61f944d9b42f93fe2fb77c9be565efabfa9292aeb8d34de3d1c8c85 and 604c940db286ab408bd60963116355428f0efa216725ca2e269639e1572fc1dd. Development services untouched; isolated worktrees/logs retained.", + "next": "After acceptance, S01 stateful TS decisions requires ADR-005 approval; R01/R11 require ADR-006. No pending ADR implicitly approved." + } } diff --git a/docs/development/backlog/tasks/F08.md b/docs/development/backlog/tasks/F08.md index ab55a734..fa376813 100644 --- a/docs/development/backlog/tasks/F08.md +++ b/docs/development/backlog/tasks/F08.md @@ -125,3 +125,11 @@ reporting: { - Rust: boundary sample after observations versus unchanged earlier risk reset; equal-time sequential risk halt still latched; first/final partial periods and exact terminal-boundary deduplication; exposure overlap/open positions/same-time owner handoff; no trade/stale marks; restore after every event including within observation groups; unchanged financial checkpoint/trace/project results. - TS/native: report format/identity/calendar/terminal-value validation; worker format/cancellation/failure guards; two sessions 100 → 110 → 99 yield +10%/−10%; partial returns retained but not annualized as full sessions; missing rates/benchmark; constant negative and nonbinary constant returns; unsupported round trips remain null; genuine zero exposure survives the additive adapter. - Run existing calculation, mapping and frontend metric/provenance fixtures, full repository checks and scoped strict test TypeScript. Worker changes require disposable PostgreSQL/Redis recovery gates. Measure reporting overhead against the accepted compact path with identical economic hashes; no timing assertions, new cache/DSL, journal deletion, or unrelated hot-loop optimization. + +## Reviewed implementation handoff — 2026-10-23 + +Implemented in `financial/reporting.rs` and replay hooks, native `FinancialReplaySession.report()`, the existing TS native/worker contract, additive `CanonicalBacktestAnalytics` types and `backtest/canonical-result.ts`. Existing reviewed calculations supply statistical reporting; no legacy DTO or default runner cutover. + +Independent review, exact owner-source integration, repository gates, disposable recovery and release-format comparisons passed. Full check initially found an incomplete decision trace in the new integration fixture; the corrected test explicitly submits every due hold and passes. See [wave handoff](../../ROADMAP.md#thirteenth-wave-execution--2026-10-23) and the canonical manifest validation record for commands, counts, hashes, initial unfavorable timings and the unchanged-artifact control. New implementation remains uncommitted. + +R05 must consume the additive contract without filling unsupported round-trip/benchmark statistics or legacy position fields with invented values. S01 does not need another reporting contract. Long-session statistical throughput remains unmeasured; the six benchmark fixtures each contain one partial account period. diff --git a/libs/calculations/README.md b/libs/calculations/README.md index 07ec1140..d50a1ef8 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -20,9 +20,10 @@ const risk = returnStatistics(returns); - `./returns`: simple/log returns, explicit percentage-point conversion, CAGR and annualization. Inputs must be finite. Invalid price baselines throw, not return zero. - CAGR is `null` for zero elapsed time, nonpositive ending capital or unrepresentable - output. Other nonrepresentable outputs throw. Annualization requires an explicit - positive number of periods/year; return statistics below intentionally use daily data. + CAGR is `null` for zero elapsed time, negative ending capital or unrepresentable + output. With positive initial capital and elapsed time, zero terminal capital has + CAGR −1. Other nonrepresentable outputs throw. Annualization requires an explicit + positive number of periods/year. - `./indicators`: O(n) batch SMA plus trailing mean, population deviation and crossover helpers shared with the supported TypeScript strategies. SMA output index 0 belongs to source index `period - 1`; incomplete batch warm-up is `[]`, scalar warm-up is @@ -42,8 +43,13 @@ const risk = returnStatistics(returns); identity: partition qualified venue/instrument IDs before calculating any feature. - `./analytics`: the existing tested fraction-based equity/drawdown, observed daily return/factor, closed-trade and performance calculations, moved from the orchestrator. - Daily statistics use 252 periods/year, UTC grouping, sample volatility and explicit - `null` for undefined ratios. Trade holding periods are minutes. Persisted strategy + `returnStatistics(returns, annualRiskFree, periodsPerYear)` supports an explicit + frequency and nullable risk-free input; omitted arguments retain the legacy 2%/252 + defaults. Null risk-free leaves target-dependent metrics unavailable while preserving + independently defined volatility/tail statistics. `drawdownAnalysis` uses numeric + timestamps without UTC grouping; `equityAnalysis` and legacy performance reporting + retain their UTC grouping. Undefined ratios are `null`, sample deviation uses n−1, + and downside deviation uses full-series RMS. Trade holding periods are minutes. Persisted strategy versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage fields in `performanceAnalysis` remain compatibility heuristics, not optimizers. diff --git a/libs/calculations/src/analytics/equity.ts b/libs/calculations/src/analytics/equity.ts index 6f48a585..3da1b89f 100644 --- a/libs/calculations/src/analytics/equity.ts +++ b/libs/calculations/src/analytics/equity.ts @@ -27,7 +27,8 @@ export function ratio(numerator: number, denominator: number): number | null { : nullable(numerator / denominator); } -export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) { +/** Sampled drawdowns only; no UTC grouping or JavaScript Date range restriction. */ +export function drawdownAnalysis(points: readonly EquityPoint[], initialCapital: number) { if (finite(initialCapital) <= 0) { throw new Error('Initial capital must be positive'); } @@ -37,8 +38,6 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n let maxDrawdown = 0; const periods: DrawdownPeriod[] = []; const underwater: EquityPoint[] = []; - const daily = new Map(); - const monthly = new Map(); for (const [index, point] of points.entries()) { finite(point.timestamp); finite(point.value); @@ -46,9 +45,6 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n throw new Error('Equity observations must be ordered'); } previousTimestamp = point.timestamp; - const iso = new Date(point.timestamp).toISOString(); - daily.set(iso.slice(0, 10), point.value); - monthly.set(iso.slice(0, 7), point.value); if (point.value >= peak) { if (active) { periods.push({ @@ -80,6 +76,24 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n if (active) { periods.push(active); } + return { + maxDrawdown, + currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0), + maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0), + periods, + underwater, + }; +} + +export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) { + const drawdown = drawdownAnalysis(points, initialCapital); + const daily = new Map(); + const monthly = new Map(); + for (const point of points) { + const iso = new Date(point.timestamp).toISOString(); + daily.set(iso.slice(0, 10), point.value); + monthly.set(iso.slice(0, 7), point.value); + } const first = points[0]; const last = points[points.length - 1]; const elapsedDays = first && last ? (last.timestamp - first.timestamp) / dayMs : 0; @@ -93,11 +107,11 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n totalReturn, annualizedReturn, elapsedDays, - maxDrawdown, - currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0), - maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0), - periods, - underwater, + maxDrawdown: drawdown.maxDrawdown, + currentDrawdown: drawdown.currentDrawdown, + maxDrawdownDuration: drawdown.maxDrawdownDuration, + periods: drawdown.periods, + underwater: drawdown.underwater, // First observed period uses starting capital; no first-day loss/gain is discarded. dailyReturns: [...periodReturns(daily, initialCapital).values()], monthlyReturns: Object.fromEntries(periodReturns(monthly, initialCapital)), diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts index 736bd17b..06e16349 100644 --- a/libs/calculations/src/analytics/index.ts +++ b/libs/calculations/src/analytics/index.ts @@ -1,4 +1,4 @@ -export { dayMs, equityAnalysis, finite, nullable, ratio } from './equity'; +export { dayMs, drawdownAnalysis, equityAnalysis, finite, nullable, ratio } from './equity'; export type { DrawdownPeriod, EquityPoint } from './equity'; export { factorStatistics, mean, returnStatistics, sampleDeviation } from './return-statistics'; export { tradeStatistics } from './trade-statistics'; diff --git a/libs/calculations/src/analytics/return-statistics.ts b/libs/calculations/src/analytics/return-statistics.ts index 3d0694ed..a6fdb072 100644 --- a/libs/calculations/src/analytics/return-statistics.ts +++ b/libs/calculations/src/analytics/return-statistics.ts @@ -12,7 +12,15 @@ export function mean(values: readonly number[]): number | null { } export function sampleDeviation(values: readonly number[]): number | null { const average = mean(values); - if (values.length < 2 || average === null) { + if (values.length < 2) { + return null; + } + // Summing identical nonbinary fractions can perturb their mean. An exactly + // constant finite series has zero variance, without an arbitrary epsilon. + if (values.every(value => value === values[0])) { + return 0; + } + if (average === null) { return null; } return nullable( @@ -20,26 +28,40 @@ export function sampleDeviation(values: readonly number[]): number | null { ); } -/** Observed daily fractions; 252 periods/year, arithmetic excess returns, full-series downside RMS. */ -export function returnStatistics(returns: readonly number[], annualRiskFree = 0.02) { - finite(annualRiskFree); +/** Periodic fractions, arithmetic excess returns and full-series downside RMS. + * Existing callers retain 252 periods/year and 2% annual risk-free defaults. + * Explicit null means the target is unavailable, not an assumed zero rate. */ +export function returnStatistics( + returns: readonly number[], + annualRiskFree: number | null = 0.02, + periodsPerYear = 252 +) { + if (annualRiskFree !== null) { + finite(annualRiskFree); + } + if (finite(periodsPerYear) <= 0) { + throw new RangeError('Periods per year must be positive'); + } for (const value of returns) { finite(value); } const average = mean(returns); const deviation = sampleDeviation(returns); - const annualExcess = average === null ? null : nullable(average * 252 - annualRiskFree); - const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(252)); + const annualExcess = + average === null || annualRiskFree === null + ? null + : nullable(average * periodsPerYear - annualRiskFree); + const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(periodsPerYear)); const downsideDeviation = - returns.length < 2 + returns.length < 2 || annualRiskFree === null ? null : nullable( Math.sqrt( returns.reduce( - (sum, value) => sum + Math.min(value - annualRiskFree / 252, 0) ** 2, + (sum, value) => sum + Math.min(value - annualRiskFree / periodsPerYear, 0) ** 2, 0 ) / returns.length - ) * Math.sqrt(252) + ) * Math.sqrt(periodsPerYear) ); const sorted = [...returns].sort((a, b) => a - b); const tail = (confidence: number) => { diff --git a/libs/calculations/src/returns.ts b/libs/calculations/src/returns.ts index fcbf056a..70a21a1b 100644 --- a/libs/calculations/src/returns.ts +++ b/libs/calculations/src/returns.ts @@ -54,9 +54,11 @@ export function cagr(start: number, end: number, years: number): number | null { if (finite(years) < 0) { throw new RangeError('Years must be nonnegative'); } - return years === 0 || end <= 0 + return years === 0 || end < 0 ? null - : nullable(Math.expm1((Math.log(end) - Math.log(start)) / years)); + : end === 0 + ? -1 + : nullable(Math.expm1((Math.log(end) - Math.log(start)) / years)); } export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number { diff --git a/libs/calculations/test/core.test.ts b/libs/calculations/test/core.test.ts index 7b3fa779..e79871e1 100644 --- a/libs/calculations/test/core.test.ts +++ b/libs/calculations/test/core.test.ts @@ -51,7 +51,7 @@ describe('reviewed shared calculation contracts', () => { test('annualization has explicit undefined CAGR and validates sampling units', () => { expect(cagr(100, 121, 2)).toBeCloseTo(0.1); expect(cagr(100, 110, 0)).toBeNull(); - expect(cagr(100, 0, 1)).toBeNull(); + expect(cagr(100, 0, 1)).toBe(-1); expect(cagr(100, -10, 1)).toBeNull(); expect(cagr(1, 2, Number.MIN_VALUE)).toBeNull(); expect(() => cagr(0, 10, 1)).toThrow(); @@ -85,7 +85,7 @@ describe('reviewed shared calculation contracts', () => { for (let end = 1; end <= prices.length; end++) { const prefix = prices.slice(0, end); expect(sma(prices, 3).slice(0, Math.max(0, end - 2))).toEqual(sma(prefix, 3)); - expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1)); + expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1)); } expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)?.goldenCross).toBe(true); expect(() => sma([1, 2], 0)).toThrow(); diff --git a/libs/calculations/test/reporting-primitives.test.ts b/libs/calculations/test/reporting-primitives.test.ts new file mode 100644 index 00000000..de7f1592 --- /dev/null +++ b/libs/calculations/test/reporting-primitives.test.ts @@ -0,0 +1,45 @@ +import { expect, test } from 'bun:test'; +import { drawdownAnalysis, equityAnalysis } from '../src/analytics/equity'; +import { cagr } from '../src/returns'; + +test('sampled drawdown handles safe-integer timestamps beyond JavaScript Date range', () => { + const points = [ + { timestamp: -Number.MAX_SAFE_INTEGER, value: 100 }, + { timestamp: 0, value: 80 }, + { timestamp: Number.MAX_SAFE_INTEGER, value: 90 }, + ]; + expect(drawdownAnalysis(points, 100).maxDrawdown).toBeCloseTo(0.2); + expect(drawdownAnalysis(points, 100).currentDrawdown).toBeCloseTo(0.1); + expect(() => drawdownAnalysis([...points].reverse(), 100)).toThrow('ordered'); + expect(() => drawdownAnalysis(points, 0)).toThrow('positive'); +}); + +test('extracted drawdowns preserve the legacy equity analysis values and recovery periods', () => { + const points = [100, 110, 80, 90, 120, 100].map((value, i) => ({ + timestamp: i * 86400000, + value, + })); + const sampled = drawdownAnalysis(points, 100); + const legacy = equityAnalysis(points, 100); + expect(legacy).toMatchObject(sampled); + expect(sampled.periods).toHaveLength(2); + expect(sampled.periods[0]?.recovery).toBe(4); + expect(sampled.periods[1]?.recovery).toBeNull(); +}); + +test('CAGR zero terminal is total loss for positive elapsed time while negative terminal is unsupported', () => { + expect(cagr(100, 0, 0.5)).toBe(-1); + expect(cagr(100, 0, 0)).toBeNull(); + expect(cagr(100, -1, 1)).toBeNull(); + expect(cagr(100, 121, 2)).toBeCloseTo(0.1); + // Legacy UTC equity reporting retains its historical zero-terminal convention. + expect( + equityAnalysis( + [ + { timestamp: 0, value: 100 }, + { timestamp: 86400000, value: 0 }, + ], + 100 + ).annualizedReturn + ).toBeNull(); +}); diff --git a/libs/calculations/test/return-statistics.test.ts b/libs/calculations/test/return-statistics.test.ts new file mode 100644 index 00000000..9b3d5525 --- /dev/null +++ b/libs/calculations/test/return-statistics.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from 'bun:test'; +import { returnStatistics, sampleDeviation } from '../src/analytics/return-statistics'; + +describe('explicit periodic return policy', () => { + test('legacy defaults remain equivalent to explicit 252 periods and 2% annual risk-free', () => { + const returns = [-0.02, 0.01, 0.03, -0.01]; + expect(returnStatistics(returns)).toEqual(returnStatistics(returns, 0.02, 252)); + }); + + test('arithmetic excess and full-series downside RMS use the declared period count', () => { + // Mean=.01, sample variance=.0008; periodic target=.12/12=.01. + // Full-series downside variance=(.02^2+0)/2=.0002. + const result = returnStatistics([-0.01, 0.03], 0.12, 12); + expect(result.volatility).toBeCloseTo(Math.sqrt(0.0008 * 12)); + expect(result.downsideDeviation).toBeCloseTo(Math.sqrt(0.0002 * 12)); + expect(result.sharpeRatio).toBeCloseTo(0); + expect(result.sortinoRatio).toBeCloseTo(0); + expect(returnStatistics([-0.01, 0.03], 0, 4).sharpeRatio).toBeCloseTo( + 0.04 / Math.sqrt(0.0008 * 4) + ); + }); + + test('constant_negative_returns have zero variance but nonzero downside and negative Sortino', () => { + for (const value of [-0.01, -0.1]) { + const result = returnStatistics([value, value, value], 0, 252); + expect(sampleDeviation([value, value, value])).toBe(0); + expect(result.volatility).toBe(0); + expect(result.sharpeRatio).toBeNull(); + expect(result.downsideDeviation).toBeCloseTo(-value * Math.sqrt(252)); + expect(result.sortinoRatio).toBeCloseTo(-Math.sqrt(252)); + } + }); + + test('zero_variance is exact without treating a small genuine deviation as zero', () => { + expect(sampleDeviation([0.1, 0.1, 0.1])).toBe(0); + expect(sampleDeviation([Number.MAX_VALUE, Number.MAX_VALUE])).toBe(0); + expect(sampleDeviation([0.1, 0.1 + Number.EPSILON])).toBeGreaterThan(0); + expect(returnStatistics([0, 0], 0)).toMatchObject({ + volatility: 0, + downsideDeviation: 0, + sharpeRatio: null, + sortinoRatio: null, + }); + expect(returnStatistics([0.01, 0.02], 0).sortinoRatio).toBeNull(); + expect(returnStatistics([0.01], 0).volatility).toBeNull(); + expect(sampleDeviation([])).toBeNull(); + expect(() => sampleDeviation([NaN, NaN])).toThrow('finite'); + }); + + test('missing risk-free leaves independent volatility and tail statistics available', () => { + const returns = Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05); + const missing = returnStatistics(returns, null, 365); + const explicitZero = returnStatistics(returns, 0, 365); + expect(missing).toMatchObject({ + sharpeRatio: null, + sortinoRatio: null, + downsideDeviation: null, + }); + for (const key of [ + 'volatility', + 'var95', + 'cvar95', + 'var99', + 'skewness', + 'kurtosis', + 'tailRatio', + ] as const) { + expect(missing[key]).toEqual(explicitZero[key]); + } + expect(explicitZero.sharpeRatio).not.toBeNull(); + }); + + test('invalid rates, period counts and observations reject', () => { + for (const periods of [0, -1, NaN, Infinity]) { + expect(() => returnStatistics([], 0, periods)).toThrow(); + } + for (const rate of [NaN, Infinity, -Infinity]) { + expect(() => returnStatistics([], rate, 252)).toThrow(); + } + expect(() => returnStatistics([Infinity], null, 252)).toThrow(); + expect(() => returnStatistics(Array(2), null, 252)).toThrow(); + }); +}); diff --git a/libs/core/types/src/canonical-analytics.ts b/libs/core/types/src/canonical-analytics.ts new file mode 100644 index 00000000..195b6d04 --- /dev/null +++ b/libs/core/types/src/canonical-analytics.ts @@ -0,0 +1,85 @@ +/** Explicit reporting inputs, independent from financial/execution policy. */ +export interface CanonicalMetricsInput { + version: 1; + periodsPerYear: number; + annualRiskFreeRate: number | null; + /** Benchmark-dependent reporting is unsupported in version 1. */ + benchmark: null; +} + +export interface CanonicalMetricsPolicy extends CanonicalMetricsInput { + calendarId: string; + calendarRevision: string; + sampling: 'account-boundary-after-observations-v1'; + marks: 'last-available-no-per-session-freshness-certification'; + returnUnit: 'fraction'; + variance: 'sample-n-minus-one'; + riskFreeConversion: 'annual-rate-divided-by-periods-per-year'; + downside: 'full-series-rms-relative-to-risk-free'; + partialPeriods: 'visible-excluded-from-periodic-statistics'; + drawdown: 'session-end-and-terminal-sampled'; + exposureBasis: 'elapsed-calendar-time'; + cagrBasis: 'elapsed-calendar-days-365'; + zeroTerminalCagr: 'negative-one-for-positive-elapsed-time'; +} + +export type CanonicalMetricUnavailableReason = + | 'nonpositive-baseline' + | 'negative-terminal-equity' + | 'zero-duration' + | 'nonfinite-result' + | 'undefined-period-return' + | 'insufficient-periods' + | 'missing-risk-free' + | 'missing-benchmark' + | 'zero-variance' + | 'zero-downside-deviation' + | 'unsupported-round-trips'; + +export interface CanonicalSessionReturn { + sessionId: string; + periodStart: number; + periodEnd: number; + partialStart: boolean; + partialEnd: boolean; + value: number | null; + /** Complete period with a defined return; an undefined complete period invalidates + * the entire periodic-statistics sequence, not just this individual sample. */ + eligible: boolean; + reason?: 'nonpositive-baseline' | 'nonfinite-result'; +} + +/** Statistical numbers are approximate reporting values, never ledger postings. */ +export interface CanonicalMetrics { + totalReturn: number | null; + cagr: number | null; + maxDrawdown: number | null; + exposureTime: number | null; + volatility: number | null; + downsideDeviation: number | null; + sharpeRatio: number | null; + sortinoRatio: number | null; + var95: number | null; + cvar95: number | null; + var99: number | null; + alpha: null; + beta: null; + informationRatio: null; + roundTripCount: null; + winRate: null; + profitFactor: null; + avgWin: null; + avgLoss: null; +} + +export interface CanonicalBacktestAnalytics { + version: 1; + policy: CanonicalMetricsPolicy; + sessionReturns: CanonicalSessionReturn[]; + completePeriodCount: number; + /** Zero if any complete-period return is undefined; do not shorten the sequence. */ + periodicSampleCount: number; + fillCount: number; + metrics: CanonicalMetrics; + unavailable: Partial>; +} diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 629fa12f..70040217 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -51,6 +51,14 @@ export type { BacktestRunTrade, BacktestRunResult, } from './backtest-run'; +export type { + CanonicalMetricsInput, + CanonicalMetricsPolicy, + CanonicalMetricUnavailableReason, + CanonicalSessionReturn, + CanonicalMetrics, + CanonicalBacktestAnalytics, +} from './canonical-analytics'; // Export helper types export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers'; diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts index c5ed38f2..9ff1b29a 100644 --- a/scripts/test/native-bindings.test.ts +++ b/scripts/test/native-bindings.test.ts @@ -73,6 +73,7 @@ describe('generated native bindings', () => { expect(binding.IncrementalSMA).toBe(IncrementalSMA); expect(binding.FinancialReplaySession).toBe(FinancialReplaySession); expect(typeof FinancialReplaySession.prototype.project).toBe('function'); + expect(typeof FinancialReplaySession.prototype.report).toBe('function'); }); it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => { diff --git a/test/integration/canonical-native-report.test.ts b/test/integration/canonical-native-report.test.ts new file mode 100644 index 00000000..d71b6afc --- /dev/null +++ b/test/integration/canonical-native-report.test.ts @@ -0,0 +1,121 @@ +import { expect, test } from 'bun:test'; +import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types'; +import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; +import { + parseReplayReportResult, + replayConfigSchema, +} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +const policy: CanonicalMetricsInput = { + version: 1, + periodsPerYear: 252, + annualRiskFreeRate: 0, + benchmark: null, +}; + +test('real native facts, worker transport and canonical analytics compose without changing finances', async () => { + const fixture = nativeReplayFixture(); + fixture.config.risk_boundaries = [1, 2, 3].map(index => ({ + ...fixture.config.matching.risk.ledger.riskSession, + sessionId: `report-session-${index}`, + startsAt: fixture.start + index * fixture.minute, + })); + const input = { + type: 'runReplayTrace' as const, + version: 1 as const, + dataset: fixture.dataset, + config: replayConfigSchema.parse(fixture.config), + eventBudget: 1, + trace: [ + { + at: fixture.start + fixture.minute, + ownerId: 'A', + intent: { + mode: 'target' as const, + targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], + }, + }, + { + at: fixture.start + 2 * fixture.minute, + ownerId: 'A', + intent: { mode: 'target' as const, targets: [] }, + }, + ], + }; + const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; + const financial = executeReplayTrace({ ...input, resultFormat: 'report' }).result; + const before = JSON.stringify(financial); + const report = buildCanonicalBacktestReport(financial, policy); + expect(financial.projection).toEqual(projection.projection); + expect(financial.view).toEqual(projection.view); + expect(report.financial).toBe(financial); + expect(JSON.stringify(financial)).toBe(before); + expect(financial.projection.valuation.cash).toBe('9975.76000000'); + expect(financial.projection.valuation.equity).toBe('10005.76000000'); + expect(financial.projection.valuation.fees).toBe('0.24000000'); + expect(financial.reporting.sessions.map(session => session.equity)).toEqual([ + '10001.76000000', + '10005.76000000', + ]); + expect(report.analytics.sessionReturns.map(session => session.eligible)).toEqual([true, true]); + expect(report.analytics.sessionReturns[0]?.value).toBeCloseTo(1.76 / 10000, 12); + expect(report.analytics.sessionReturns[1]?.value).toBeCloseTo(4 / 10001.76, 12); + expect(report.analytics.metrics.totalReturn).toBeCloseTo(5.76 / 10000, 12); + expect(report.analytics.metrics.exposureTime).toBe(1); + expect(report.analytics.metrics.maxDrawdown).toBe(0); + expect(report.analytics.metrics.sharpeRatio).not.toBeNull(); + expect(report.analytics.metrics.sortinoRatio).toBeNull(); + expect(report.analytics.unavailable.sortinoRatio).toBe('zero-downside-deviation'); + expect(report.analytics.fillCount).toBe(1); + expect(report.analytics.metrics.roundTripCount).toBeNull(); + expect(report.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips'); + expect(financial.view.portfolio.positions[0]?.quantity).toBe('2.00000000'); + + const worker = new NativeBacktestWorker(); + const raw = await worker.execute( + { ...input, resultFormat: 'report', eventBudget: 64 }, + new AbortController().signal, + () => {} + ); + const transported = parseReplayReportResult(raw, financial.identity, input.config); + expect(buildCanonicalBacktestReport(transported, policy)).toEqual(report); + + const missingRate = buildCanonicalBacktestReport(financial, { + ...policy, + annualRiskFreeRate: null, + }); + expect(missingRate.financial).toBe(financial); + expect(missingRate.analytics.metrics.sharpeRatio).toBeNull(); + expect(missingRate.analytics.unavailable.sharpeRatio).toBe('missing-risk-free'); + expect(missingRate.analytics.metrics.volatility).toBe(report.analytics.metrics.volatility); +}); + +test('real no-trade native reporting retains genuine zero metrics through the canonical adapter', () => { + const fixture = nativeReplayFixture(); + const financial = executeReplayTrace({ + type: 'runReplayTrace', + version: 1, + dataset: fixture.dataset, + config: fixture.config, + eventBudget: 64, + trace: [1, 2].map(index => ({ + at: fixture.start + index * fixture.minute, + ownerId: 'A', + intent: { mode: 'target' as const, targets: [] }, + })), + resultFormat: 'report', + }).result; + const report = buildCanonicalBacktestReport(financial, policy); + expect(report.analytics.metrics.totalReturn).toBe(0); + expect(report.analytics.metrics.exposureTime).toBe(0); + expect(report.analytics.metrics.cagr).toBe(0); + expect(report.analytics.fillCount).toBe(0); + expect(report.analytics.sessionReturns[0]?.value).toBe(0); + expect(report.analytics.sessionReturns[0]?.partialEnd).toBe(true); + expect(report.analytics.periodicSampleCount).toBe(0); + expect(report.analytics.metrics.volatility).toBeNull(); + expect(report.analytics.unavailable.volatility).toBe('insufficient-periods'); +}); diff --git a/test/integration/canonical-result.test.ts b/test/integration/canonical-result.test.ts new file mode 100644 index 00000000..54ca6560 --- /dev/null +++ b/test/integration/canonical-result.test.ts @@ -0,0 +1,353 @@ +import { describe, expect, test } from 'bun:test'; +import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types'; +import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { + parseReplayReportValue, + type ReplayConfig, + type ReplayReportResult, +} from '../../apps/stock/orchestrator/src/contracts/native-replay'; + +const policy: CanonicalMetricsInput = { + version: 1, + periodsPerYear: 252, + annualRiskFreeRate: 0, + benchmark: null, +}; +const money = (value: number | string) => parseFinancialDecimal(String(value)); + +/** Hand-authored statistical input fixtures validated by the accepted wire schema. + * Native reporting tests, not these fixtures, establish financial transition validity. */ +function fixture( + equities = [110, 99], + options: { + initial?: number; + times?: number[]; + partialStart?: boolean; + partialEnd?: boolean; + occupiedIntervals?: { start: number; end: number }[]; + } = {} +): ReplayReportResult { + const initial = options.initial ?? 100; + // Two sessions can end on the same UTC date; UTC grouping would lose a return. + const start = Date.parse('2024-01-01T23:30:00Z'); + const times = + options.times ?? Array.from({ length: equities.length + 1 }, (_, i) => start + i * 3600000); + const tradeStart = times[0]!, + tradeEnd = times.at(-1)!; + const identity = { + version: 1 as const, + sessionId: 'analytics-fixture', + datasetHash: 'a'.repeat(64), + }; + const riskSession = (index: number) => ({ + calendarId: 'account-test', + calendarRevision: 'revision-7', + sessionId: `session-${index}`, + startsAt: index === 0 && options.partialStart ? tradeStart - 1000 : times[index]!, + }); + const config: ReplayConfig = { + matching: { + risk: { + ledger: { + version: 1, + sessionId: identity.sessionId, + accountId: 'account', + baseCurrency: 'USD', + reserveOwnerId: 'reserve', + ownerIds: ['A'], + initialCapital: money(initial), + riskSession: riskSession(0), + }, + feeRate: '0', + maxOrderQuantity: '1000', + maxPositionQuantity: '1000', + maxSymbolExposure: '1000000', + maxGrossExposure: '1000000', + maxDailyLoss: '1000000', + maxDrawdownAmount: '1000000', + maxMarkAgeMs: 86400000, + }, + owners: [{ ownerId: 'A', mode: 'Target' }], + series: [{ instrumentId: 'X.US', seriesId: 'X.US:1m', mode: 'Open' }], + halfSpreadRate: '0', + slippageRate: '0', + latencyMs: 0, + }, + participation_rate: '1', + cadence: [{ owner_id: 'A', series_ids: ['X.US:1m'] }], + allow_exploratory: false, + risk_boundaries: [], + }; + const ledger = config.matching.risk.ledger; + config.risk_boundaries = times + .slice(1, options.partialEnd ? -1 : undefined) + .map((_, index) => riskSession(index + 1)); + const final = money(equities.at(-1)!); + const occupiedIntervals = options.occupiedIntervals ?? []; + const lastRisk = config.risk_boundaries.at(-1) ?? ledger.riskSession; + return parseReplayReportValue( + { + identity, + status: 'complete', + format: 'report', + reportingVersion: 1, + projectionVersion: 1, + financialVersion: 1, + manifest: { version: 2, hash: identity.datasetHash, bounds: { tradeStart, tradeEnd } }, + policy: config, + view: { + admissionRevision: 0, + portfolio: { + version: 1, + sessionId: identity.sessionId, + accountId: ledger.accountId, + revision: 0, + baseCurrency: ledger.baseCurrency, + reserveOwnerId: ledger.reserveOwnerId, + cash: final, + positions: [], + fees: [], + riskSession: lastRisk, + }, + equity: final, + availableCash: final, + orders: [], + reservations: [], + risk: { + dailyBaseline: money(initial), + peakEquity: money(initial), + dailyHalted: false, + drawdownHalted: false, + riskSession: lastRisk, + lastEventTime: tradeEnd, + }, + }, + projection: { + valuation: { + cash: final, + markedHoldings: '0', + equity: final, + remainingCost: '0', + realizedGrossPnl: '0', + unrealizedPnl: '0', + fees: '0', + owners: [], + }, + fills: [], + }, + reporting: { + calendarId: ledger.riskSession.calendarId, + calendarRevision: ledger.riskSession.calendarRevision, + tradeStart, + tradeEnd, + initialEquity: money(initial), + sampling: 'account-boundary-after-observations-v1', + exposureBasis: 'elapsed-calendar-time', + sessions: equities.map((equity, index) => ({ + session: riskSession(index), + periodStart: times[index], + periodEnd: times[index + 1], + partialStart: index === 0 && !!options.partialStart, + partialEnd: index === equities.length - 1 && !!options.partialEnd, + equity: money(equity), + })), + occupiedIntervals, + occupiedMs: String( + occupiedIntervals.reduce((sum, i) => sum + BigInt(i.end) - BigInt(i.start), 0n) + ), + elapsedMs: String(BigInt(tradeEnd) - BigInt(tradeStart)), + }, + limitations: ['fixture availability'], + modelLimitations: ['Equal-time asset marks are sequential; portfolio risk is not atomic.'], + }, + identity + ); +} + +function analytics(financial = fixture(), selectedPolicy = policy) { + const output = buildCanonicalBacktestReport(financial, selectedPolicy).analytics; + for (const [key, value] of Object.entries(output.metrics)) { + if (value === null) { + expect(output.unavailable[key as keyof typeof output.metrics]).toBeDefined(); + } else { + expect(Number.isFinite(value)).toBe(true); + expect(output.unavailable[key as keyof typeof output.metrics]).toBeUndefined(); + } + } + return output; +} + +describe('canonical statistical reporting', () => { + test('two_session_marks retain final session, fractional units and explicit calendar conventions', () => { + const output = analytics(); + expect(output.sessionReturns).toHaveLength(2); + expect(output.sessionReturns[0]?.value).toBeCloseTo(0.1); + expect(output.sessionReturns[1]?.value).toBeCloseTo(-0.1); + expect(output.metrics.totalReturn).toBeCloseTo(-0.01); + expect(output.metrics.maxDrawdown).toBeCloseTo(0.1); + expect(output.metrics.volatility).toBeCloseTo(Math.sqrt(0.02 * 252)); + expect(output.metrics.downsideDeviation).toBeCloseTo(Math.sqrt(0.005 * 252)); + expect(output.metrics.sharpeRatio).toBeCloseTo(0); + expect(output.metrics.sortinoRatio).toBeCloseTo(0); + expect(output.periodicSampleCount).toBe(2); + expect(output.policy).toMatchObject({ + calendarId: 'account-test', + calendarRevision: 'revision-7', + sampling: 'account-boundary-after-observations-v1', + drawdown: 'session-end-and-terminal-sampled', + exposureBasis: 'elapsed-calendar-time', + cagrBasis: 'elapsed-calendar-days-365', + returnUnit: 'fraction', + marks: 'last-available-no-per-session-freshness-certification', + }); + }); + + test('partial initial and final returns remain visible but do not become complete statistical periods', () => { + const output = analytics(fixture([110, 99, 198, 99], { partialStart: true, partialEnd: true })); + expect(output.sessionReturns.map(s => s.eligible)).toEqual([false, true, true, false]); + expect(output.sessionReturns.map(s => s.partialStart)).toEqual([true, false, false, false]); + expect(output.sessionReturns.at(-1)?.value).toBeCloseTo(-0.5); + expect(output.completePeriodCount).toBe(2); + expect(output.periodicSampleCount).toBe(2); + // Only -.1 and +1: mean .45, sample variance .605. + expect(output.metrics.volatility).toBeCloseTo(Math.sqrt(0.605 * 252)); + expect(output.metrics.sharpeRatio).toBeCloseTo((0.45 * 252) / Math.sqrt(0.605 * 252)); + expect(output.metrics.totalReturn).toBeCloseTo(-0.01); + }); + + test('undefined complete return invalidates the entire periodic sequence without dropping history', () => { + const output = analytics(fixture([0, 0, 0])); + expect(output.sessionReturns.map(s => s.value)).toEqual([-1, null, null]); + expect(output.sessionReturns[1]?.reason).toBe('nonpositive-baseline'); + expect(output.completePeriodCount).toBe(3); + expect(output.periodicSampleCount).toBe(0); + for (const key of [ + 'volatility', + 'downsideDeviation', + 'sharpeRatio', + 'sortinoRatio', + 'var95', + 'cvar95', + 'var99', + ] as const) { + expect(output.metrics[key]).toBeNull(); + expect(output.unavailable[key]).toBe('undefined-period-return'); + } + expect(output.metrics.totalReturn).toBe(-1); + expect(output.metrics.cagr).toBe(-1); + }); + + test('constant_negative_returns and zero_variance distinguish Sharpe from Sortino', () => { + const negative = analytics(fixture([90, 81])); + expect(negative.metrics.volatility).toBe(0); + expect(negative.metrics.sharpeRatio).toBeNull(); + expect(negative.unavailable.sharpeRatio).toBe('zero-variance'); + expect(negative.metrics.sortinoRatio).toBeCloseTo(-Math.sqrt(252)); + const zero = analytics(fixture([100, 100])); + expect(zero.metrics.totalReturn).toBe(0); + expect(zero.metrics.volatility).toBe(0); + expect(zero.metrics.downsideDeviation).toBe(0); + expect(zero.metrics.sortinoRatio).toBeNull(); + expect(zero.unavailable.sortinoRatio).toBe('zero-downside-deviation'); + }); + + test('missing rate and benchmark remain unavailable; explicit zero is not missing', () => { + const missing = analytics(fixture(), { ...policy, annualRiskFreeRate: null }); + for (const key of ['sharpeRatio', 'sortinoRatio', 'downsideDeviation'] as const) { + expect(missing.metrics[key]).toBeNull(); + expect(missing.unavailable[key]).toBe('missing-risk-free'); + } + expect(missing.metrics.volatility).not.toBeNull(); + expect(missing.unavailable.beta).toBe('missing-benchmark'); + expect(analytics().metrics.sharpeRatio).not.toBeNull(); + for (const input of [ + { ...policy, benchmark: 'SPY' }, + { ...policy, annualRiskFreeRate: undefined }, + { ...policy, periodsPerYear: 0 }, + { ...policy, periodsPerYear: Infinity }, + { ...policy, version: 2 }, + { ...policy, extra: true }, + ]) { + expect(() => + buildCanonicalBacktestReport(fixture(), input as CanonicalMetricsInput) + ).toThrow(); + } + }); + + test('exposure consumes the canonical union and includes terminal open-position occupancy', () => { + // Rust supplies the union [1,7) of overlapping positions [1,5),[3,7). + const financial = fixture([100], { + times: [0, 10], + occupiedIntervals: [ + { start: 1, end: 7 }, + { start: 8, end: 10 }, + ], + }); + expect(analytics(financial).metrics.exposureTime).toBe(0.8); + expect(analytics(fixture([100], { times: [0, 10] })).metrics.exposureTime).toBe(0); + expect( + analytics(fixture([100], { times: [0, 10], occupiedIntervals: [{ start: 0, end: 10 }] })) + .metrics.exposureTime + ).toBe(1); + }); + + test('financial facts and limitations are preserved; fill count is not round-trip count', () => { + const financial = fixture(); + financial.projection.fills.push({ + commandId: 'command', + eventTime: financial.reporting.tradeStart, + ownerId: 'A', + decision: { ownerId: 'A', decisionId: 'decision', sequence: 0 }, + orderId: 'order', + fillId: 'fill', + instrumentId: 'X0.US', + side: 'buy', + quantity: money(1), + price: money(10), + fee: { feeId: 'fee', amount: money(1) }, + cashDelta: money(-10), + quantityDelta: money(1), + releasedBasis: money(0), + realizedGrossPnl: money(0), + }); + const before = structuredClone(financial); + const result = buildCanonicalBacktestReport(financial, policy); + expect(result.financial).toBe(financial); + expect(result.financial).toEqual(before); + expect(result.analytics.fillCount).toBe(1); + for (const key of ['roundTripCount', 'winRate', 'profitFactor', 'avgWin', 'avgLoss'] as const) { + expect(result.analytics.metrics[key]).toBeNull(); + expect(result.analytics.unavailable[key]).toBe('unsupported-round-trips'); + } + expect(result.analytics).not.toHaveProperty('positions'); + }); + + test('extreme supported timestamps preserve integer durations without Date coercion', () => { + const min = -Number.MAX_SAFE_INTEGER, + max = Number.MAX_SAFE_INTEGER; + const financial = fixture([110, 99], { + times: [min, 0, max], + occupiedIntervals: [{ start: min, end: max }], + }); + expect(financial.reporting.elapsedMs).toBe('18014398509481982'); + const output = analytics(financial); + expect(output.metrics.exposureTime).toBe(1); + expect(output.metrics.maxDrawdown).toBeCloseTo(0.1); + expect(output.metrics.cagr).not.toBeNull(); + }); + + test('insufficient complete periods and nonpositive initial baseline have explicit reasons', () => { + const partial = analytics(fixture([110], { partialEnd: true })); + expect(partial.sessionReturns[0]?.value).toBeCloseTo(0.1); + expect(partial.completePeriodCount).toBe(0); + expect(partial.unavailable.volatility).toBe('insufficient-periods'); + const zero = analytics(fixture([0], { initial: 0 })); + expect(zero.unavailable.totalReturn).toBe('nonpositive-baseline'); + expect(zero.unavailable.cagr).toBe('nonpositive-baseline'); + expect(zero.unavailable.maxDrawdown).toBe('nonpositive-baseline'); + const overflow = analytics(fixture([200], { times: [0, 1] })); + expect(overflow.metrics.totalReturn).toBe(1); + expect(overflow.metrics.cagr).toBeNull(); + expect(overflow.unavailable.cagr).toBe('nonfinite-result'); + }); +}); diff --git a/test/integration/native-replay-report.test.ts b/test/integration/native-replay-report.test.ts new file mode 100644 index 00000000..60174d5e --- /dev/null +++ b/test/integration/native-replay-report.test.ts @@ -0,0 +1,311 @@ +import type { ChildProcess } from 'node:child_process'; +import { describe, expect, test } from 'bun:test'; +import { FinancialReplaySession } from '@stock-bot/engine'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { + executeReplayTrace, + NativeReplaySession, + prepareReplayLoad, + runReplayConformance, +} from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; +import { + parseReplayProjectionResult, + parseReplayReportResult, + parseReplayResult, + replayConfigSchema, +} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +const hold = () => ({ mode: 'target' as const, targets: [] }); +const buy = () => ({ + mode: 'target' as const, + targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], +}); +function request(twoSessions = false) { + const f = nativeReplayFixture(); + if (twoSessions) { + f.config.risk_boundaries = [2, 3].map(n => ({ + ...f.config.matching.risk.ledger.riskSession, + sessionId: `risk-${n}`, + startsAt: f.start + n * f.minute, + })); + } + return { + type: 'runReplayTrace' as const, + version: 1 as const, + dataset: f.dataset, + config: replayConfigSchema.parse(f.config), + eventBudget: 1, + trace: [ + { at: f.start + f.minute, ownerId: 'A', intent: buy() }, + { at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() }, + ], + }; +} + +describe('authoritative replay reporting', () => { + test('two_session_marks and occupancy preserve compact financial facts and earlier reset', () => { + const input = request(true), + f = nativeReplayFixture(); + const projected = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; + let reset: string | undefined; + const output = runReplayConformance( + new NativeReplaySession(prepareReplayLoad(input.dataset, input.config)), + (_owner, context) => (context.barrier.at === f.start + f.minute ? buy() : hold()), + { + resultFormat: 'report', + eventBudget: 1, + onProgress: step => { + if ( + step.step.type === 'decisionBatch' && + step.step.barrier.at === f.start + 2 * f.minute + ) { + reset = step.step.view.risk.dailyBaseline; + } + }, + } + ).result; + expect(output.projection).toEqual(projected.projection); + expect(output.view).toEqual(projected.view); + expect(output.policy).toEqual(projected.policy); + expect(output.modelLimitations).toEqual(projected.modelLimitations); + expect(reset).toBe('9999.76000000'); + expect(output.reporting).toEqual({ + calendarId: 'account', + calendarRevision: '1', + tradeStart: f.start + f.minute, + tradeEnd: f.start + 3 * f.minute, + initialEquity: parseFinancialDecimal('10000.00000000'), + sampling: 'account-boundary-after-observations-v1', + exposureBasis: 'elapsed-calendar-time', + sessions: [ + { + session: input.config.matching.risk.ledger.riskSession, + periodStart: f.start + f.minute, + periodEnd: f.start + 2 * f.minute, + partialStart: true, + partialEnd: false, + equity: parseFinancialDecimal('10001.76000000'), + }, + { + session: input.config.risk_boundaries[0]!, + periodStart: f.start + 2 * f.minute, + periodEnd: f.start + 3 * f.minute, + partialStart: false, + partialEnd: false, + equity: parseFinancialDecimal('10005.76000000'), + }, + ], + occupiedIntervals: [{ start: f.start + f.minute, end: f.start + 3 * f.minute }], + occupiedMs: '120000', + elapsedMs: '120000', + }); + expect(output).not.toHaveProperty('receipts'); + expect(executeReplayTrace({ ...input, resultFormat: 'report' }).result).toEqual(output); + }); + + test('native report is read-only and rejects incomplete, failed, wrong identity and disposed states', () => { + const f = nativeReplayFixture(), + load = prepareReplayLoad(f.dataset, f.config); + const native = new FinancialReplaySession(JSON.stringify(load)), + identity = JSON.stringify(load.identity); + expect(() => native.report(identity)).toThrow('complete'); + expect(() => native.report(JSON.stringify({ ...load.identity, version: 2 }))).toThrow(); + expect(() => native.report(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow( + 'identity' + ); + let sequence = 0; + try { + for (;;) { + const step = JSON.parse( + native.advance(JSON.stringify({ identity: load.identity, eventBudget: 1 })) + ).step; + if (step.type === 'complete') { + break; + } + if (step.type === 'failed') { + throw new Error(step.diagnostic); + } + if (step.type === 'decisionBatch') { + native.submit( + JSON.stringify({ + identity: load.identity, + barrierId: step.barrier.barrier_id, + decisions: [ + { + version: 1, + sessionId: load.identity.sessionId, + barrierId: step.barrier.barrier_id, + revision: step.barrier.revision, + decision: { + ownerId: 'A', + decisionId: `direct-${sequence}`, + sequence: sequence++, + }, + intent: hold(), + }, + ], + }) + ); + } + } + const trace = native.finalize(identity), + projection = native.project(identity), + report = native.report(identity); + expect(native.report(identity)).toBe(report); + expect(native.finalize(identity)).toBe(trace); + expect(native.project(identity)).toBe(projection); + const parsed = parseReplayReportResult(report, load.identity); + expect(parsed.reporting.occupiedMs).toBe('0'); + expect(parsed.reporting.sessions).toHaveLength(1); + expect(parsed.reporting.sessions[0]?.partialEnd).toBe(true); + } finally { + native.dispose(); + } + expect(() => native.report(identity)).toThrow('disposed'); + load.prepared.bars[0]!.high = '792281625142643375935.43950335'; + load.prepared.bars[0]!.close = '792281625142643375935.43950335'; + const failed = new FinancialReplaySession(JSON.stringify(load)); + try { + const step = JSON.parse( + failed.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 })) + ).step; + const submission = JSON.parse( + failed.submit( + JSON.stringify({ + identity: load.identity, + barrierId: step.barrier.barrier_id, + decisions: [ + { + version: 1, + sessionId: load.identity.sessionId, + barrierId: step.barrier.barrier_id, + revision: step.barrier.revision, + decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 }, + intent: buy(), + }, + ], + }) + ) + ); + expect(submission.outcome.status).toHaveProperty('Failed'); + expect(() => failed.report(identity)).toThrow('complete'); + } finally { + failed.dispose(); + } + }); + + test('strict reporting format, identity, calendar, partition, terminal and union validation', () => { + const input = request(true), + result = executeReplayTrace({ ...input, resultFormat: 'report' }).result; + expect(() => parseReplayProjectionResult(JSON.stringify(result), result.identity)).toThrow(); + expect(() => parseReplayResult(JSON.stringify(result), result.identity)).toThrow(); + for (const mutate of [ + (r: any) => (r.format = 'projection'), + (r: any) => (r.reportingVersion = 2), + (r: any) => (r.projectionVersion = 2), + (r: any) => (r.financialVersion = 2), + (r: any) => (r.receipts = []), + (r: any) => (r.identity.sessionId = 'wrong'), + (r: any) => (r.reporting.calendarId = 'wrong'), + (r: any) => (r.reporting.calendarRevision = 'wrong'), + (r: any) => r.reporting.tradeStart++, + (r: any) => (r.reporting.initialEquity = '9999'), + (r: any) => (r.reporting.sessions.at(-1).equity = '1'), + (r: any) => r.reporting.sessions[0].periodEnd++, + (r: any) => (r.reporting.sessions[0].partialStart = false), + (r: any) => (r.reporting.sessions.at(-1).partialEnd = true), + (r: any) => r.reporting.sessions.push(r.reporting.sessions[0]), + (r: any) => (r.reporting.occupiedMs = '0120000'), + (r: any) => (r.reporting.occupiedMs = '120001'), + (r: any) => (r.reporting.elapsedMs = '120001'), + (r: any) => r.reporting.occupiedIntervals[0].start--, + (r: any) => r.reporting.occupiedIntervals.push(r.reporting.occupiedIntervals[0]), + (r: any) => (r.policy.matching.risk.feeRate = '0.5'), + ]) { + const changed = structuredClone(result); + mutate(changed); + expect(() => + parseReplayReportResult(JSON.stringify(changed), result.identity, input.config) + ).toThrow(); + } + const projection = executeReplayTrace({ ...input, resultFormat: 'projection' }).result; + expect(() => parseReplayReportResult(JSON.stringify(projection), result.identity)).toThrow(); + }); + + test('report duration validation uses exact integers before subtracting timestamps', () => { + const input = request(); + input.trace = input.trace.map(row => ({ ...row, intent: hold() })); + const result = executeReplayTrace({ ...input, resultFormat: 'report' }).result; + const start = -Number.MAX_SAFE_INTEGER, + end = Number.MAX_SAFE_INTEGER - 1; + const session = { ...result.policy.matching.risk.ledger.riskSession, startsAt: start }; + result.policy.matching.risk.ledger.riskSession = session; + Object.assign(result.manifest.bounds as object, { tradeStart: start, tradeEnd: end }); + Object.assign(result.reporting, { + tradeStart: start, + tradeEnd: end, + elapsedMs: '18014398509481981', + sessions: [ + { + session, + periodStart: start, + periodEnd: end, + partialStart: false, + partialEnd: true, + equity: result.view.equity, + }, + ], + }); + expect( + parseReplayReportResult(JSON.stringify(result), result.identity).reporting.elapsedMs + ).toBe('18014398509481981'); + result.reporting.elapsedMs = String(end - start); + expect(() => parseReplayReportResult(JSON.stringify(result), result.identity)).toThrow( + 'duration' + ); + }); + + test('worker captures report format and preserves failure and post-result cancellation guards', async () => { + const input = { ...request(), resultFormat: 'report' as const }, + worker = new NativeBacktestWorker(); + const expected = executeReplayTrace(input).result; + const mutable = { ...input }; + const raw = await worker.execute(mutable, new AbortController().signal, () => { + (mutable as { resultFormat: string }).resultFormat = 'projection'; + }); + expect(parseReplayReportResult(raw, expected.identity, input.config)).toEqual(expected); + const fixture = new NativeBacktestWorker( + new URL('../fixtures/native-replay-worker.ts', import.meta.url) + ); + for (const mode of [ + 'wrong-format', + 'wrong-policy', + 'wrong-account', + 'wrong-session', + 'crash', + ]) { + const bad = { ...request(), resultFormat: 'report' as const }; + bad.config.matching.risk.ledger.accountId = mode; + await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow(); + } + const blocked = { ...request(), resultFormat: 'report' as const }; + blocked.config.matching.risk.ledger.accountId = 'result-then-block'; + const cancellation = new AbortController(); + let observed = false; + const running = fixture.execute(blocked, cancellation.signal, () => {}); + const child = (fixture as unknown as { active: ChildProcess }).active; + child.on('message', (message: any) => { + if (message.type === 'result') { + observed = true; + cancellation.abort(new Error('report cancelled')); + } + }); + await expect(running).rejects.toThrow('report cancelled'); + expect(observed).toBe(true); + expect( + JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format + ).toBe('report'); + }); +});