use crate::rng::GameRng;
use crate::sectors::{Sector, SECTORS};
const UNIVERSE_STREAM: u32 = 21;
const PE_SCATTER: f64 = 1.7;
const BOOK_SCATTER: f64 = 2.4;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct GeneratedInstrument {
pub ticker: String,
pub sector: &'static str,
pub initial_price: f64,
pub shares_outstanding: f64,
pub eps: f64,
pub book_value_per_share: f64,
pub revenue_growth: f64,
pub avg_volume: f64,
pub beta: f64,
pub short_interest: f64,
}
fn between(rng: &mut GameRng, lo: f64, hi: f64) -> f64 {
lo + rng.next_f64() * (hi - lo)
}
fn log_between(rng: &mut GameRng, lo: f64, hi: f64) -> f64 {
let t = rng.next_f64();
crate::mathx::exp(crate::mathx::log(lo) + t * (crate::mathx::log(hi) - crate::mathx::log(lo)))
}
fn ticker_for(index: usize) -> String {
let a = index / (26 * 26) % 26;
let b = index / 26 % 26;
let c = index % 26;
[
(b'A' + a as u8) as char,
(b'A' + b as u8) as char,
(b'A' + c as u8) as char,
]
.iter()
.collect()
}
pub fn random_universe(n: usize, seed: u64) -> Vec<GeneratedInstrument> {
let mut rng = GameRng::new(seed, UNIVERSE_STREAM);
let mut out = Vec::with_capacity(n);
for i in 0..n {
let sector: &Sector = &SECTORS[i % SECTORS.len()];
let market_cap = log_between(&mut rng, 2.0e8, 2.0e12);
let initial_price = log_between(&mut rng, 3.0, 600.0);
let shares_outstanding = market_cap / initial_price;
let pe_ratio = sector.avg_pe
* log_between(&mut rng, 1.0 / PE_SCATTER, PE_SCATTER);
let loss_maker = rng.next_f64() < 0.11;
let eps = if loss_maker {
-initial_price * between(&mut rng, 0.01, 0.09)
} else {
initial_price / pe_ratio
};
let book_centre = initial_price / crate::fair_value::LOSS_MAKING_PRICE_TO_BOOK;
let book_value_per_share = log_between(
&mut rng,
book_centre / BOOK_SCATTER,
book_centre * BOOK_SCATTER,
);
let growth_centre = (sector.avg_pe - 10.0) / 100.0;
let revenue_growth = growth_centre + between(&mut rng, -0.06, 0.14);
let turnover = between(&mut rng, 0.001, 0.02);
let avg_volume = crate::mathx::max(1000.0, shares_outstanding * turnover);
let beta = crate::mathx::max(0.15, sector.volatility * between(&mut rng, 0.6, 1.35));
let short_interest = shares_outstanding * log_between(&mut rng, 0.004, 0.30);
out.push(GeneratedInstrument {
ticker: ticker_for(i),
sector: sector.key,
initial_price,
shares_outstanding,
eps,
book_value_per_share,
revenue_growth,
avg_volume,
beta,
short_interest,
});
}
out
}
#[non_exhaustive]
pub struct InstrumentInit {
pub ticker: String,
pub sector: String,
pub initial_price: f64,
pub shares_outstanding: f64,
pub eps: Option<f64>,
pub book_value_per_share: Option<f64>,
pub revenue_growth: Option<f64>,
pub avg_volume: f64,
pub beta: f64,
pub short_interest: f64,
}
impl InstrumentInit {
pub fn new(
ticker: impl Into<String>,
sector: impl Into<String>,
initial_price: f64,
shares_outstanding: f64,
) -> Self {
InstrumentInit {
ticker: ticker.into(),
sector: sector.into(),
initial_price,
shares_outstanding,
eps: None,
book_value_per_share: None,
revenue_growth: None,
avg_volume: 1_000_000.0,
beta: 1.0,
short_interest: 0.0,
}
}
}
impl InstrumentInit {
pub fn market_cap(&self) -> f64 {
self.initial_price * self.shares_outstanding
}
pub fn to_tick_company(&self, index: usize) -> crate::market::TickCompany {
let sector = crate::sectors::by_key(&self.sector)
.expect("validated at construction");
crate::market::TickCompany {
id: format!("{}-{index}", self.ticker),
ticker: self.ticker.clone(),
sector: self.sector.clone(),
is_bankrupt: false,
is_public: true,
stock: crate::market::TickStock {
price: self.initial_price,
previous_close: self.initial_price,
previous_tick_price: None,
open: self.initial_price,
high: self.initial_price,
low: self.initial_price,
volume: 0.0,
avg_volume: self.avg_volume,
shares_outstanding: self.shares_outstanding,
market_cap: self.market_cap(),
mispricing_s: None,
mispricing_s_prev_close: None,
mispricing_momentum: None,
fair_value_offset: None,
buyback_log_shares: None,
dividend: None,
maker_inventory: None,
garch_variance: sector.base_daily_variance(),
garch_cascade: [sector.base_daily_variance();
crate::market::garch::CASCADE_MAX],
last_daily_return: None,
beta: Some(self.beta),
short_interest: self.short_interest,
float: self.shares_outstanding,
},
sector_volatility: Some(sector.volatility),
sector_avg_pe: Some(sector.avg_pe),
eps: self.eps,
book_value_per_share: self.book_value_per_share,
revenue_growth: self.revenue_growth,
}
}
}
impl GeneratedInstrument {
pub fn to_init(&self) -> InstrumentInit {
InstrumentInit {
ticker: self.ticker.clone(),
sector: self.sector.to_string(),
initial_price: self.initial_price,
shares_outstanding: self.shares_outstanding,
eps: Some(self.eps),
book_value_per_share: Some(self.book_value_per_share),
revenue_growth: Some(self.revenue_growth),
avg_volume: self.avg_volume,
beta: self.beta,
short_interest: self.short_interest,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_same_seed_gives_the_same_universe() {
assert_eq!(random_universe(50, 7), random_universe(50, 7));
}
#[test]
fn a_different_seed_gives_a_different_universe() {
assert_ne!(random_universe(50, 7), random_universe(50, 8));
}
#[test]
fn a_larger_universe_extends_a_smaller_one() {
let small = random_universe(20, 3);
let large = random_universe(60, 3);
assert_eq!(small[..], large[..20]);
}
#[test]
fn every_sector_is_represented_once_the_universe_is_large_enough() {
let u = random_universe(12, 1);
let mut seen: Vec<&str> = u.iter().map(|i| i.sector).collect();
seen.sort_unstable();
seen.dedup();
assert_eq!(seen.len(), 12);
}
#[test]
fn it_contains_loss_makers_and_profitable_names() {
let u = random_universe(200, 11);
let losers = u.iter().filter(|i| i.eps < 0.0).count();
assert!(losers > 5, "only {losers} loss-makers in 200");
assert!(losers < 60, "{losers} loss-makers in 200 is not a market");
}
#[test]
fn market_caps_span_every_spread_tier() {
let u = random_universe(300, 5);
let caps: Vec<f64> = u
.iter()
.map(|i| i.initial_price * i.shares_outstanding)
.collect();
assert!(caps.iter().any(|c| *c < 1.0e9), "no small caps");
assert!(caps.iter().any(|c| *c > 5.0e10), "no mega caps");
}
#[test]
fn everything_generated_is_finite_and_sane() {
for inst in random_universe(500, 13) {
assert!(inst.initial_price > 0.0 && inst.initial_price.is_finite());
assert!(inst.shares_outstanding > 0.0 && inst.shares_outstanding.is_finite());
assert!(inst.avg_volume >= 1000.0 && inst.avg_volume.is_finite());
assert!(inst.beta > 0.0 && inst.beta.is_finite());
assert!(inst.eps.is_finite());
assert!(inst.book_value_per_share > 0.0);
assert!(inst.revenue_growth.is_finite());
}
}
#[test]
fn tickers_are_unique_and_positional() {
let u = random_universe(300, 2);
assert_eq!(u[0].ticker, "AAA");
assert_eq!(u[26].ticker, "ABA");
let mut t: Vec<&str> = u.iter().map(|i| i.ticker.as_str()).collect();
t.sort_unstable();
t.dedup();
assert_eq!(t.len(), 300, "tickers collided");
}
#[test]
fn a_generated_roster_opens_at_its_own_fair_value() {
let u = random_universe(4000, 7);
let mut means: Vec<f64> = Vec::new();
for neutral in [crate::fair_value::NEUTRAL_DISCOUNT_RATE, 0.0456, 0.0482] {
let economy = crate::fair_value::EconomyValuationInputs {
corporate_bond_yield: Some(neutral * 100.0),
federal_funds_rate: neutral * 100.0,
qe_pe_boost: Some(0.0),
qe_assets_ratio: None,
};
let mut total = 0.0;
let mut above = 0usize;
let mut on_book = 0usize;
for inst in &u {
let sector = crate::sectors::by_key(inst.sector).expect("generated");
let breakdown = crate::fair_value::compute_fair_value_with(
&crate::fair_value::CompanyValuationInputs {
sector_avg_pe: Some(sector.avg_pe),
eps: Some(inst.eps),
book_value_per_share: Some(inst.book_value_per_share),
revenue_growth: Some(inst.revenue_growth),
},
&economy,
0.0,
1.0,
0.0,
neutral,
);
let s = crate::mathx::log(inst.initial_price / breakdown.fair_value);
total += s;
if s > 0.0 {
above += 1;
}
if breakdown.book_value_path {
on_book += 1;
}
}
let mean = total / u.len() as f64;
means.push(mean);
assert!(
mean.abs() < 0.02,
"at neutral {neutral}, day-zero mean log(price/fair_value) is \n {mean}, not centred"
);
let fraction = above as f64 / u.len() as f64;
assert!(
(fraction - 0.5).abs() < 0.03,
"at neutral {neutral}, {fraction} of names open above fair value, \n not about half"
);
assert!(on_book > 200, "only {on_book} names on the book path");
assert!(on_book < 800, "{on_book} names on the book path is not a market");
}
assert!(
means.windows(2).all(|w| w[0].to_bits() == w[1].to_bits()),
"the day-zero mean depends on the neutral rate: {means:?}"
);
}
#[test]
fn the_valuation_ratios_are_symmetric_in_log_rather_than_in_the_ratio() {
for scatter in [PE_SCATTER, BOOK_SCATTER] {
let midpoint_in_log = crate::mathx::log(1.0 / scatter)
+ crate::mathx::log(scatter);
assert!(
midpoint_in_log.abs() < 1e-15,
"range around {scatter} is off-centre in log by {midpoint_in_log}"
);
}
let midpoint = (0.55 + 1.6) / 2.0;
let geometric = crate::mathx::exp((crate::mathx::log(0.55)
+ crate::mathx::log(1.6))
/ 2.0);
assert!(midpoint > 1.0 && geometric < 1.0);
let was = crate::mathx::log(1.6 / 0.55);
let now = 2.0 * crate::mathx::log(PE_SCATTER);
assert!((now / was - 1.0).abs() < 0.02, "pe scatter width moved");
let was_book = crate::mathx::log(1.4 / 0.25);
let now_book = 2.0 * crate::mathx::log(BOOK_SCATTER);
assert!((now_book / was_book - 1.0).abs() < 0.02, "book scatter width moved");
}
#[test]
fn reconciling_the_roster_did_not_move_the_stream() {
let u = random_universe(40, 111);
assert_eq!(u[0].ticker, "AAA");
assert_eq!(u[0].sector, "technology");
assert_eq!(u[0].initial_price, 200.45251589262966);
assert_eq!(u[0].shares_outstanding, 19483093.73920724);
assert_eq!(u[0].revenue_growth, 0.2776378159318119);
assert_eq!(u[0].avg_volume, 75955.40594971534);
assert_eq!(u[0].beta, 0.92810710019432);
assert_eq!(u[0].short_interest, 3531201.404338788);
}
#[test]
fn generation_does_not_touch_the_engine_stream() {
assert_ne!(UNIVERSE_STREAM, 99, "must not be the MAIN stream");
}
}