use crate::agent_book::{daily_sigma, daily_volume};
use crate::market::TickCompany;
use crate::mathx;
use crate::order_book::Side;
pub const LABEL_PREFIX: &str = "population:";
pub const SESSION_TICKS: u32 = 390;
pub const MAX_LOOKBACK: u32 = 60;
const FLAT_VERSION: f64 = 1.0;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Policy {
Trend {
lookback: u32,
scale: f64,
},
Reversion {
lookback: u32,
scale: f64,
},
Liquidity {
half_life: f64,
scale: f64,
vix_calm: f64,
vix_stress: f64,
},
Detector {
memory: f64,
bucket: u32,
lead: u32,
hold: u32,
max_spread: f64,
},
Crowd {
momentum: bool,
lookback: u32,
offset: u32,
top_k: u32,
buffer: u32,
stop: f64,
recover: f64,
},
}
impl Policy {
pub fn kind(&self) -> &'static str {
match self {
Policy::Trend { .. } => "trend",
Policy::Reversion { .. } => "reversion",
Policy::Liquidity { .. } => "liquidity",
Policy::Detector { .. } => "detector",
Policy::Crowd { .. } => "crowd",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Participant {
pub name: String,
pub size: f64,
pub rate: f64,
pub interval: u32,
pub band: f64,
pub policy: Policy,
}
impl Participant {
pub fn new(
name: impl Into<String>,
size: f64,
rate: f64,
interval: u32,
band: f64,
policy: Policy,
) -> Self {
Participant { name: name.into(), size, rate, interval, band, policy }
}
pub fn label(&self) -> String {
format!("{LABEL_PREFIX}{}", self.name)
}
fn check(&self) -> Result<(), String> {
let finite_pos = |v: f64| v.is_finite() && v > 0.0;
if self.name.is_empty() || self.name.chars().any(|c| c.is_whitespace()) {
return Err(format!(
"a participant's name is non-empty with no spaces, got {:?}",
self.name
));
}
if !finite_pos(self.size) || !finite_pos(self.rate) {
return Err(format!(
"{}: size and rate must be finite and above zero",
self.name
));
}
if self.interval == 0 || self.interval > SESSION_TICKS {
return Err(format!(
"{}: interval must be 1 to {SESSION_TICKS} ticks",
self.name
));
}
if !(self.band.is_finite() && (0.0..1.0).contains(&self.band)) {
return Err(format!("{}: band must be in [0, 1)", self.name));
}
match &self.policy {
Policy::Trend { lookback, scale } | Policy::Reversion { lookback, scale } => {
if *lookback == 0 || *lookback > MAX_LOOKBACK {
return Err(format!(
"{}: lookback must be 1 to {MAX_LOOKBACK} sessions",
self.name
));
}
if !finite_pos(*scale) {
return Err(format!(
"{}: scale must be finite and above zero",
self.name
));
}
}
Policy::Liquidity {
half_life,
scale,
vix_calm,
vix_stress,
} => {
if !finite_pos(*half_life) || !finite_pos(*scale) {
return Err(format!(
"{}: half_life and scale must be finite and above zero",
self.name
));
}
if !(vix_calm.is_finite() && vix_stress.is_finite() && vix_calm < vix_stress) {
return Err(format!("{}: vix_calm must be below vix_stress", self.name));
}
}
Policy::Detector {
memory,
bucket,
lead,
hold,
max_spread,
} => {
if !finite_pos(*max_spread) {
return Err(format!(
"{}: max_spread must be finite and above zero",
self.name
));
}
if !finite_pos(*memory) {
return Err(format!(
"{}: memory must be finite and above zero",
self.name
));
}
if *bucket == 0 || *bucket > SESSION_TICKS {
return Err(format!(
"{}: bucket must be 1 to {SESSION_TICKS} ticks",
self.name
));
}
if lead + hold >= SESSION_TICKS - bucket {
return Err(format!(
"{}: lead and hold together must be shorter than a session less one bucket",
self.name
));
}
}
Policy::Crowd {
lookback,
top_k,
offset,
stop,
recover,
..
} => {
if SESSION_TICKS % self.interval != 0 {
return Err(format!(
"{}: a crowd's interval must divide the session's {SESSION_TICKS} ticks",
self.name
));
}
if *lookback == 0
|| lookback % self.interval != 0
|| *lookback > MAX_LOOKBACK * SESSION_TICKS
{
return Err(format!(
"{}: a crowd's lookback is a whole number of intervals, at most \
{MAX_LOOKBACK} sessions of {SESSION_TICKS} ticks",
self.name
));
}
if *top_k == 0 {
return Err(format!("{}: top_k must be at least 1", self.name));
}
if *offset >= self.interval {
return Err(format!("{}: offset must be below the interval", self.name));
}
if !(stop.is_finite() && *stop >= 0.0) {
return Err(format!(
"{}: stop must be finite and not negative",
self.name
));
}
if !(recover.is_finite() && *recover > 0.0 && *recover <= 1.0) {
return Err(format!(
"{}: recover must be above 0 and at most 1",
self.name
));
}
}
}
Ok(())
}
fn buckets(&self) -> usize {
match self.policy {
Policy::Detector { bucket, .. } => SESSION_TICKS.div_ceil(bucket) as usize,
_ => 0,
}
}
fn samples(&self) -> usize {
match self.policy {
Policy::Crowd { lookback, .. } => (lookback / self.interval) as usize + 1,
_ => 0,
}
}
}
const CROWD_SCALARS: usize = 4;
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct ParticipantState {
pub position: Vec<f64>,
pub cash: Vec<f64>,
pub volume: Vec<f64>,
pub notional: Vec<f64>,
pub orders: f64,
pub average: Vec<f64>,
pub profile: Vec<Vec<f64>>,
pub samples: Vec<f64>,
pub crowd: Vec<f64>,
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct PopulationRun {
pub fingerprint: String,
pub participants: Vec<Participant>,
pub tickers: Vec<String>,
pub day: Option<i64>,
pub last: Vec<f64>,
pub closes: Vec<f64>,
pub depth: usize,
pub states: Vec<ParticipantState>,
pub owners: Vec<usize>,
pub gates: Vec<f64>,
}
pub const GATE_WINDOW: u32 = 5;
fn profile_owners(participants: &[Participant]) -> Vec<usize> {
let key = |p: &Participant| match p.policy {
Policy::Detector { memory, bucket, .. } => Some((memory.to_bits(), bucket)),
_ => None,
};
(0..participants.len())
.map(|k| match key(&participants[k]) {
Some(own) => (0..k).find(|&j| key(&participants[j]) == Some(own)).unwrap_or(k),
None => k,
})
.collect()
}
pub type Order = (usize, usize, f64);
impl PopulationRun {
pub fn new(
fingerprint: String,
participants: Vec<Participant>,
companies: &[TickCompany],
) -> Result<Self, String> {
if participants.is_empty() {
return Err("a population needs at least one participant".to_string());
}
for (k, p) in participants.iter().enumerate() {
p.check()?;
if participants[..k].iter().any(|q| q.name == p.name) {
return Err(format!("two participants are named {:?}", p.name));
}
}
let depth = participants
.iter()
.map(|p| match p.policy {
Policy::Trend { lookback, .. } | Policy::Reversion { lookback, .. } => {
lookback as usize
}
_ => 0,
})
.max()
.unwrap_or(0);
let mut run = PopulationRun {
fingerprint,
participants,
tickers: Vec::new(),
day: None,
last: Vec::new(),
closes: Vec::new(),
depth,
states: Vec::new(),
owners: Vec::new(),
gates: Vec::new(),
};
run.owners = profile_owners(&run.participants);
run.states = vec![ParticipantState::default(); run.participants.len()];
for (k, p) in run.participants.iter().enumerate() {
if matches!(p.policy, Policy::Crowd { .. }) {
run.states[k].crowd = vec![1.0, 0.0, 0.0, 0.0];
}
}
run.align(companies);
Ok(run)
}
pub fn align(&mut self, companies: &[TickCompany]) {
if self.tickers.len() == companies.len()
&& self
.tickers
.iter()
.zip(companies)
.all(|(t, c)| *t == c.ticker)
{
return;
}
let old: Vec<String> = std::mem::take(&mut self.tickers);
let n = companies.len();
let from: Vec<Option<usize>> = companies
.iter()
.map(|c| old.iter().position(|t| *t == c.ticker))
.collect();
let pick = |v: &[f64], width: usize, empty: f64| -> Vec<f64> {
let mut out = vec![empty; n * width];
for (i, f) in from.iter().enumerate() {
if let Some(j) = f {
if (j + 1) * width <= v.len() {
out[i * width..(i + 1) * width]
.copy_from_slice(&v[j * width..(j + 1) * width]);
}
}
}
out
};
let last: Vec<f64> = companies
.iter()
.enumerate()
.map(|(i, c)| match from[i] {
Some(j) if j < self.last.len() => self.last[j],
_ => c.stock.price,
})
.collect();
self.closes = pick(&self.closes, self.depth, f64::NAN);
self.gates = if self.shares_gates() {
pick(&self.gates, 2, f64::NAN)
} else {
Vec::new()
};
self.last = last;
for (k, p) in self.participants.iter().enumerate() {
let s = &mut self.states[k];
s.position = pick(&s.position, 1, 0.0);
s.cash = pick(&s.cash, 1, 0.0);
s.volume = pick(&s.volume, 1, 0.0);
s.notional = pick(&s.notional, 1, 0.0);
match p.policy {
Policy::Liquidity { .. } => {
let avg = pick(&s.average, 1, f64::NAN);
s.average = avg;
}
Policy::Crowd { .. } => {
let width = p.samples();
let samples = pick(&s.samples, width, f64::NAN);
s.samples = samples;
}
Policy::Detector { .. } if self.owners[k] != k => {
s.profile = Vec::new();
}
Policy::Detector { .. } => {
s.profile = from
.iter()
.map(|f| {
f.and_then(|j| s.profile.get(j).cloned())
.unwrap_or_default()
})
.collect();
}
_ => {}
}
}
self.tickers = companies.iter().map(|c| c.ticker.clone()).collect();
}
fn close(&self, index: usize, lag: usize) -> f64 {
if lag == 0 || lag > self.depth {
return f64::NAN;
}
self.closes[index * self.depth + self.depth - lag]
}
pub fn roll_day(&mut self, day: i64) {
let d = self.depth;
if d > 0 {
for i in 0..self.last.len() {
let row = &mut self.closes[i * d..(i + 1) * d];
row.rotate_left(1);
row[d - 1] = self.last[i];
}
}
for (k, p) in self.participants.iter().enumerate() {
if let Policy::Crowd { recover, .. } = p.policy {
let g = &mut self.states[k].crowd[0];
if *g < 1.0 {
*g = mathx::min(1.0, *g + recover);
}
}
if let Policy::Detector { memory, .. } = p.policy {
if self.owners[k] != k {
continue;
}
let alpha = 1.0 - mathx::pow(0.5, 1.0 / memory);
let b = p.buckets();
for row in self.states[k].profile.iter_mut().filter(|r| !r.is_empty()) {
for slot in 0..b {
let (m, v, x) = (row[slot], row[b + slot], row[2 * b + slot]);
let d = x - m;
row[slot] = m + alpha * d;
row[b + slot] = (1.0 - alpha) * (v + alpha * d * d);
row[2 * b + slot] = 0.0;
}
}
}
}
self.day = Some(day);
}
pub fn observe_flow(&mut self, index: usize, tick: u32, net: f64, volume: f64) {
if net == 0.0 || !(volume > 0.0) {
return;
}
for (k, p) in self.participants.iter().enumerate() {
if let Policy::Detector { bucket, .. } = p.policy {
if self.owners[k] != k {
continue;
}
let b = p.buckets();
let slot = std::cmp::min((tick / bucket) as usize, b - 1);
if let Some(row) = self.states[k].profile.get_mut(index) {
if row.is_empty() {
*row = vec![0.0; 3 * b];
}
row[2 * b + slot] += net / volume;
}
}
}
}
pub fn after_tick(&mut self, companies: &[TickCompany]) {
for (i, c) in companies.iter().enumerate() {
if let Some(slot) = self.last.get_mut(i) {
*slot = c.stock.price;
}
}
for (k, p) in self.participants.iter().enumerate() {
if let Policy::Liquidity { half_life, .. } = p.policy {
let a = 1.0 - mathx::pow(0.5, 1.0 / half_life);
let s = &mut self.states[k];
for (i, c) in companies.iter().enumerate() {
let price = c.stock.price;
if !(price > 0.0) {
continue;
}
let x = mathx::log(price);
if let Some(avg) = s.average.get_mut(i) {
*avg = if avg.is_nan() {
x
} else {
*avg + a * (x - *avg)
};
}
}
}
}
}
pub fn shares_gates(&self) -> bool {
self.participants
.iter()
.filter(|p| matches!(p.policy, Policy::Detector { .. }))
.count()
> 1
}
fn turn(&self, k: usize, tick: u32) -> bool {
let p = &self.participants[k];
match p.policy {
Policy::Crowd { offset, .. } => tick % p.interval == offset,
_ => tick % p.interval == (k as u32) % p.interval,
}
}
fn crowd_book(&self, k: usize, companies: &[TickCompany]) -> Option<Vec<f64>> {
let p = &self.participants[k];
let Policy::Crowd {
momentum,
top_k,
buffer,
..
} = p.policy
else {
return None;
};
let width = p.samples();
let rows = &self.states[k].samples;
let held = &self.states[k].position;
let mut ranked: Vec<(f64, usize)> = Vec::new();
for (i, c) in companies.iter().enumerate() {
if c.is_bankrupt || !c.is_public || !(c.stock.price > 0.0) {
continue;
}
let Some(row) = rows.get(i * width..(i + 1) * width) else {
continue;
};
let (past, now) = (row[0], row[width - 1]);
if !(past > 0.0) || !(now > 0.0) {
continue;
}
let r = now / past - 1.0;
ranked.push((if momentum { -r } else { r }, i));
}
let n = ranked.len();
let kk = std::cmp::min(top_k as usize, n / 2);
if kk == 0 {
return None;
}
let keep = std::cmp::min(kk + buffer as usize, n / 2);
ranked.sort_by(|a, b| {
a.0.partial_cmp(&b.0)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| companies[a.1].ticker.cmp(&companies[b.1].ticker))
});
let mut book = vec![0.0; companies.len()];
for (rank, (_, i)) in ranked.iter().enumerate() {
let q = held.get(*i).copied().unwrap_or(0.0);
if rank < kk || (rank < keep && q > 0.0) {
book[*i] = 1.0;
} else if rank >= n - kk || (rank >= n - keep && q < 0.0) {
book[*i] = -1.0;
}
}
Some(book)
}
pub fn prepare(&mut self, tick: u32, companies: &[TickCompany]) {
for k in 0..self.participants.len() {
let Policy::Crowd { stop, .. } = self.participants[k].policy else {
continue;
};
if !self.turn(k, tick) {
continue;
}
let width = self.participants[k].samples();
{
let s = &mut self.states[k];
let mut made = 0.0;
for (i, c) in companies.iter().enumerate() {
if let Some(row) = s.samples.get_mut(i * width..(i + 1) * width) {
row.rotate_left(1);
let price = c.stock.price;
row[width - 1] = if price > 0.0 { price } else { f64::NAN };
let q = s.position.get(i).copied().unwrap_or(0.0);
let (was, now) = (row[width - 2], row[width - 1]);
if q != 0.0 && was > 0.0 && now > 0.0 {
made += q * (now - was);
}
}
}
s.crowd[3] += made;
}
if stop <= 0.0 {
continue;
}
let Some(book) = self.crowd_book(k, companies) else {
continue;
};
let size = self.participants[k].size;
let mut gross = 0.0;
for (i, c) in companies.iter().enumerate() {
if book[i] != 0.0 {
gross += size * daily_volume(c) * c.stock.price;
}
}
if !(gross > 0.0) {
continue;
}
let s = &mut self.states[k];
let pnl = s.crowd[3];
if pnl > s.crowd[1] {
s.crowd[1] = pnl;
}
if s.crowd[0] > 0.0 && s.crowd[1] - pnl > stop * gross {
s.crowd[0] = 0.0;
s.crowd[1] = pnl;
s.crowd[2] += 1.0;
}
}
}
fn predicted(&self, k: usize, index: usize, tick: u32) -> f64 {
let p = &self.participants[k];
let Policy::Detector {
bucket, lead, hold, ..
} = p.policy
else {
return 0.0;
};
let b = p.buckets();
let row = match self.states[self.owners[k]].profile.get(index) {
Some(r) if !r.is_empty() => r,
_ => return 0.0,
};
let (row_m, row_v) = (&row[..b], &row[b..2 * b]);
let first = (tick as i64 - hold as i64).div_euclid(bucket as i64);
let last = (tick as i64 + lead as i64).div_euclid(bucket as i64);
let mut total = 0.0;
for at in first..=last {
let slot = at.rem_euclid(b as i64) as usize;
let (m, v) = (row_m[slot], row_v[slot]);
let m2 = m * m;
if m2 + v > 0.0 {
let r = m2 / (m2 + v);
total += m * r * r;
}
}
total
}
pub fn decide(
&self,
tick: u32,
companies: &[TickCompany],
market_sigma_daily: f64,
vix: f64,
) -> Vec<Order> {
let mut orders = Vec::new();
for (k, p) in self.participants.iter().enumerate() {
if !self.turn(k, tick) {
continue;
}
let s = &self.states[k];
let book = if matches!(p.policy, Policy::Crowd { .. }) {
self.crowd_book(k, companies)
} else {
None
};
for (i, c) in companies.iter().enumerate() {
if c.is_bankrupt || !c.is_public {
continue;
}
let price = c.stock.price;
let volume = daily_volume(c);
let sigma = daily_sigma(c, market_sigma_daily);
if !(price > 0.0) || !(volume > 0.0) || !(sigma > 0.0) {
continue;
}
let cap = p.size * volume;
let target = match p.policy {
Policy::Trend { lookback, scale } | Policy::Reversion { lookback, scale } => {
let past = self.close(i, lookback as usize);
if !(past > 0.0) {
continue;
}
let m = mathx::log(price / past) / (sigma * mathx::sqrt(lookback as f64));
let sign = if matches!(p.policy, Policy::Trend { .. }) {
1.0
} else {
-1.0
};
sign * cap * mathx::clamp(m / scale, -1.0, 1.0)
}
Policy::Liquidity {
half_life,
scale,
vix_calm,
vix_stress,
} => {
let avg = s.average.get(i).copied().unwrap_or(f64::NAN);
if avg.is_nan() {
continue;
}
let w =
mathx::clamp((vix_stress - vix) / (vix_stress - vix_calm), 0.0, 1.0);
let z = (mathx::log(price) - avg)
/ (sigma * mathx::sqrt(half_life / SESSION_TICKS as f64));
-cap * w * mathx::clamp(z / scale, -1.0, 1.0)
}
Policy::Crowd { .. } => {
let side = book.as_ref().map(|b| b[i]).unwrap_or(0.0);
if side == 0.0 && s.position[i] == 0.0 {
continue;
}
side * s.crowd[0] * cap
}
Policy::Detector { .. } => {
let pred = self.predicted(k, i, tick);
if pred == 0.0 && s.position[i] == 0.0 {
continue;
}
mathx::clamp(pred * volume, -cap, cap)
}
};
let gap = target - s.position[i];
if gap.abs() <= p.band * cap {
continue;
}
let step = mathx::clamp(gap, -p.rate * volume, p.rate * volume).trunc();
if step != 0.0 {
orders.push((k, i, step));
}
}
}
orders
}
pub fn max_spread(&self, k: usize) -> Option<f64> {
match self.participants[k].policy {
Policy::Detector { max_spread, .. } => Some(max_spread),
_ => None,
}
}
pub fn adds(&self, k: usize, index: usize, signed: f64) -> bool {
let held = self.states[k].position[index];
held == 0.0 || (held > 0.0) == (signed > 0.0)
}
pub fn book_fill(&mut self, k: usize, index: usize, side: Side, quantity: f64, price: f64) {
let s = &mut self.states[k];
let signed = match side {
Side::Buy => quantity,
Side::Sell => -quantity,
};
s.position[index] += signed;
s.cash[index] -= signed * price;
s.volume[index] += quantity;
s.notional[index] += quantity * price;
}
pub fn book_order(&mut self, k: usize) {
self.states[k].orders += 1.0;
}
pub fn to_flat(&self) -> Vec<f64> {
let mut out = vec![
FLAT_VERSION,
self.tickers.len() as f64,
self.depth as f64,
if self.day.is_some() { 1.0 } else { 0.0 },
self.day.unwrap_or(0) as f64,
];
out.extend_from_slice(&self.last);
out.extend_from_slice(&self.closes);
if self.shares_gates() {
out.extend_from_slice(&self.gates);
}
for (k, s) in self.states.iter().enumerate() {
out.push(s.orders);
for v in [&s.position, &s.cash, &s.volume, &s.notional, &s.average] {
out.push(v.len() as f64);
out.extend_from_slice(v);
}
out.push(s.profile.len() as f64);
for row in &s.profile {
out.push(row.len() as f64);
out.extend_from_slice(row);
}
if matches!(self.participants[k].policy, Policy::Crowd { .. }) {
out.push(s.samples.len() as f64);
out.extend_from_slice(&s.samples);
out.extend_from_slice(&s.crowd);
}
}
out
}
pub fn set_flat(&mut self, tickers: Vec<String>, flat: &[f64]) -> Result<(), String> {
let bad = |what: &str| format!("snapshot field population.state is malformed: {what}");
let mut at = 0usize;
let mut take = |count: usize| -> Result<&[f64], String> {
let end = at
.checked_add(count)
.filter(|e| *e <= flat.len())
.ok_or_else(|| bad("too short"))?;
let out = &flat[at..end];
at = end;
Ok(out)
};
let head = take(5)?.to_vec();
if head[0] != FLAT_VERSION {
return Err(bad("unknown layout version"));
}
let n = head[1] as usize;
if head[1] != n as f64 || n != tickers.len() {
return Err(bad("the name count does not match the tickers"));
}
if head[2] != self.depth as f64 {
return Err(bad("the close depth does not match this population"));
}
let day = if head[3] == 1.0 {
Some(head[4] as i64)
} else {
None
};
let last = take(n)?.to_vec();
let closes = take(n * self.depth)?.to_vec();
let gates = if self.shares_gates() {
take(2 * n)?.to_vec()
} else {
Vec::new()
};
let mut states = Vec::with_capacity(self.participants.len());
for (k, p) in self.participants.iter().enumerate() {
let mut s = ParticipantState {
orders: take(1)?[0],
..Default::default()
};
let widths = [
n,
n,
n,
n,
if matches!(p.policy, Policy::Liquidity { .. }) {
n
} else {
0
},
];
let mut parts: Vec<Vec<f64>> = Vec::with_capacity(5);
for w in widths {
let len = take(1)?[0];
if len != w as f64 {
return Err(bad(
"an array's length does not match this population and roster",
));
}
parts.push(take(w)?.to_vec());
}
let mut it = parts.into_iter();
s.position = it.next().unwrap_or_default();
s.cash = it.next().unwrap_or_default();
s.volume = it.next().unwrap_or_default();
s.notional = it.next().unwrap_or_default();
s.average = it.next().unwrap_or_default();
let rows = take(1)?[0];
let detector = matches!(p.policy, Policy::Detector { .. }) && self.owners[k] == k;
if rows != if detector { n as f64 } else { 0.0 } {
return Err(bad(
"the detector's profiles do not match this population and roster",
));
}
for _ in 0..rows as usize {
let len = take(1)?[0];
if len != 0.0 && len != (3 * p.buckets()) as f64 {
return Err(bad("a detector profile has the wrong length"));
}
s.profile.push(take(len as usize)?.to_vec());
}
if matches!(p.policy, Policy::Crowd { .. }) {
let len = take(1)?[0];
if len != (n * p.samples()) as f64 {
return Err(bad(
"a crowd's prices do not match this population and roster",
));
}
s.samples = take(len as usize)?.to_vec();
s.crowd = take(CROWD_SCALARS)?.to_vec();
}
states.push(s);
}
if at != flat.len() {
return Err(bad("too long"));
}
self.tickers = tickers;
self.day = day;
self.last = last;
self.closes = closes;
self.gates = gates;
self.states = states;
Ok(())
}
pub fn participant_of(&self, label: &str) -> Option<usize> {
let name = label.strip_prefix(LABEL_PREFIX)?;
self.participants.iter().position(|p| p.name == name)
}
}
pub fn is_population_label(label: &str) -> bool {
label.starts_with(LABEL_PREFIX)
}
#[cfg(test)]
mod tests {
use super::*;
fn detector() -> Participant {
Participant {
name: "d".into(),
size: 0.02,
rate: 0.002,
interval: 1,
band: 0.0,
policy: Policy::Detector {
memory: 1.0,
bucket: 5,
lead: 20,
hold: 10,
max_spread: 1.0,
},
}
}
fn run(p: Participant) -> PopulationRun {
PopulationRun {
fingerprint: "x".into(),
depth: 0,
states: vec![ParticipantState::default()],
participants: vec![p],
tickers: Vec::new(),
day: None,
last: Vec::new(),
closes: Vec::new(),
owners: vec![0],
gates: Vec::new(),
}
}
fn with_names(mut r: PopulationRun, n: usize) -> PopulationRun {
r.tickers = (0..n).map(|i| format!("N{i}")).collect();
r.last = vec![10.0; n];
let b = r.participants[0].buckets();
let s = &mut r.states[0];
s.position = vec![0.0; n];
s.cash = vec![0.0; n];
s.volume = vec![0.0; n];
s.notional = vec![0.0; n];
let _ = b;
s.profile = vec![Vec::new(); n];
r
}
#[test]
fn the_detector_trusts_flow_that_recurs_and_not_flow_that_does_not() {
let mut steady = with_names(run(detector()), 1);
let mut erratic = with_names(run(detector()), 1);
for day in 0..8 {
steady.observe_flow(0, 50, 100.0, 10_000.0);
if day % 2 == 0 {
erratic.observe_flow(0, 50, 200.0, 10_000.0);
}
steady.roll_day(day + 1);
erratic.roll_day(day + 1);
}
let a = steady.predicted(0, 0, 45);
let b = erratic.predicted(0, 0, 45);
assert!(a > 0.0095 && a < 0.0101, "steady prediction {a}");
assert!(b < 0.5 * a, "erratic {b} against steady {a}");
}
#[test]
fn the_flat_state_round_trips() {
let mut r = with_names(run(detector()), 3);
r.observe_flow(1, 7, 50.0, 1000.0);
r.roll_day(4);
r.book_fill(0, 2, Side::Buy, 12.0, 9.5);
let flat = r.to_flat();
let mut s = r.clone();
s.states[0].position[2] = 0.0;
s.set_flat(r.tickers.clone(), &flat).unwrap();
let bits = |v: Vec<f64>| v.into_iter().map(f64::to_bits).collect::<Vec<_>>();
assert_eq!(bits(s.to_flat()), bits(r.to_flat()));
assert!(s
.set_flat(r.tickers.clone(), &flat[..flat.len() - 1])
.is_err());
}
}