use crate::economy::EconomyState;
use crate::market::{
get_market_status, intraday_fraction, intraday_volume, GameTime, MarketStatus, OrderVolume,
};
use crate::market_maker::{quote_ladder, LadderParams, MakerInventory, QuoteParams, MARKET_MAKER_ID};
use crate::mathx;
use crate::microstructure::{
decompose, maker_delta_from_fills, vix_spread_multiplier, BOOK_LEVELS, INVENTORY_LIMIT_LEVELS,
};
use crate::order_book::{OrderBook, Side, SubmitOptions};
pub const RATE_SECTOR: &str = "rates";
pub const CARRY_DAYS: f64 = 252.0;
pub const INVENTORY_HALF_LIFE_TICKS: f64 = 15.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CurvePoint {
Treasury2Y,
Treasury10Y,
InvestmentGrade,
}
impl CurvePoint {
pub fn as_str(self) -> &'static str {
match self {
CurvePoint::Treasury2Y => "treasury_2y",
CurvePoint::Treasury10Y => "treasury_10y",
CurvePoint::InvestmentGrade => "investment_grade",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RateSpec {
pub ticker: &'static str,
pub name: &'static str,
pub point: CurvePoint,
pub duration: f64,
pub convexity: f64,
pub spread_bps: f64,
pub avg_volume: f64,
pub units_outstanding: f64,
pub initial_price: f64,
}
pub const RATE_SPECS: [RateSpec; 3] = [
RateSpec {
ticker: "UST2Y",
name: "Simulated 2-year constant-maturity US Treasury index (not a real security)",
point: CurvePoint::Treasury2Y,
duration: 1.9,
convexity: 4.6,
spread_bps: 0.6,
avg_volume: 2.2e6,
units_outstanding: 3.0e8,
initial_price: 100.0,
},
RateSpec {
ticker: "UST10Y",
name: "Simulated 10-year constant-maturity US Treasury index (not a real security)",
point: CurvePoint::Treasury10Y,
duration: 8.5,
convexity: 84.0,
spread_bps: 0.6,
avg_volume: 4.6e6,
units_outstanding: 3.0e8,
initial_price: 100.0,
},
RateSpec {
ticker: "IGCORP",
name: "Simulated investment-grade US corporate bond index (not a real security)",
point: CurvePoint::InvestmentGrade,
duration: 7.0,
convexity: 100.0,
spread_bps: 0.8,
avg_volume: 1.4e7,
units_outstanding: 3.0e8,
initial_price: 100.0,
},
];
pub fn spec_for(ticker: &str) -> Option<&'static RateSpec> {
RATE_SPECS.iter().find(|s| s.ticker == ticker)
}
pub fn tickers() -> Vec<&'static str> {
RATE_SPECS.iter().map(|s| s.ticker).collect()
}
pub fn curve_yield(point: CurvePoint, economy: &EconomyState, ig_spread: f64) -> f64 {
match point {
CurvePoint::Treasury2Y => crate::units::percent_to_fraction(economy.treasury_yield_2y),
CurvePoint::Treasury10Y => crate::units::percent_to_fraction(economy.treasury_yield_10y),
CurvePoint::InvestmentGrade => {
crate::units::percent_to_fraction(economy.treasury_yield_10y) + ig_spread
}
}
}
pub fn credit_spread(economy: &EconomyState) -> f64 {
crate::units::percent_to_fraction(economy.corporate_bond_yield)
- crate::units::percent_to_fraction(economy.treasury_yield_10y)
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Repricing {
pub carry: f64,
pub duration: f64,
pub convexity: f64,
}
impl Repricing {
pub fn new(duration: f64, convexity: f64, dy: f64, carry_yield: f64) -> Self {
let dy = if convexity > 0.0 { mathx::min(dy, duration / convexity) } else { dy };
Repricing {
carry: carry_yield / CARRY_DAYS,
duration: -duration * dy,
convexity: 0.5 * convexity * dy * dy,
}
}
pub fn total(&self) -> f64 {
self.carry + self.duration + self.convexity
}
pub fn apply(&self, level: f64) -> f64 {
level * (1.0 + self.total())
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RateInstrument {
pub spec: RateSpec,
pub level: f64,
pub marked_yield: f64,
pub price: f64,
pub previous_close: f64,
pub open: f64,
pub high: f64,
pub low: f64,
pub volume: f64,
pub avg_volume: f64,
pub units_outstanding: f64,
pub maker_inventory: f64,
pub day_carry: f64,
pub day_duration: f64,
pub day_convexity: f64,
pub tick_shock: f64,
pub tick_absorbed: f64,
pub repriced_pending: f64,
pub tick_repriced: f64,
}
impl RateInstrument {
pub fn new(spec: RateSpec, initial_price: f64, avg_volume: f64, units_outstanding: f64) -> Self {
RateInstrument {
spec,
level: initial_price,
marked_yield: 0.0,
price: initial_price,
previous_close: initial_price,
open: initial_price,
high: initial_price,
low: initial_price,
volume: 0.0,
avg_volume,
units_outstanding,
maker_inventory: 0.0,
day_carry: 0.0,
day_duration: 0.0,
day_convexity: 0.0,
tick_shock: 0.0,
tick_absorbed: 0.0,
repriced_pending: 0.0,
tick_repriced: 0.0,
}
}
pub fn market_cap(&self) -> f64 {
self.price * self.units_outstanding
}
pub fn half_spread_bps(&self, vix: f64) -> f64 {
self.spec.spread_bps / 2.0 * vix_spread_multiplier(vix)
}
pub fn base_size(&self) -> f64 {
mathx::max(1.0, (self.avg_volume / 100.0).floor())
}
fn inventory_limit(&self) -> f64 {
mathx::max(1.0, self.base_size() * INVENTORY_LIMIT_LEVELS)
}
pub fn quoted_mid(&self, vix: f64) -> f64 {
self.quoted_mid_at(self.level, vix)
}
pub fn quoted_mid_at(&self, level: f64, vix: f64) -> f64 {
if self.maker_inventory == 0.0 {
return level;
}
let load = mathx::clamp(self.maker_inventory / self.inventory_limit(), -1.0, 1.0);
let half_spread = level * (self.half_spread_bps(vix) / 10_000.0);
level - load * half_spread
}
pub fn level_at(&self, dy: f64) -> f64 {
if dy == 0.0 {
return self.level;
}
Repricing::new(self.spec.duration, self.spec.convexity, dy, 0.0).apply(self.level)
}
pub fn book(&self, vix: f64) -> OrderBook {
self.book_at(self.level, vix)
}
pub fn book_at(&self, level: f64, vix: f64) -> OrderBook {
let mut book = OrderBook::new(self.spec.ticker.to_string(), Some(self.price));
if !(level > 0.0) {
return book;
}
let base_size = self.base_size();
let (bids, asks) = quote_ladder(&LadderParams {
quote: QuoteParams {
fair_value: level,
half_spread_bps: self.half_spread_bps(vix),
base_size,
inventory: MakerInventory {
position: self.maker_inventory,
limit: self.inventory_limit(),
},
..QuoteParams::default()
},
levels: BOOK_LEVELS,
level_step: 0.5,
});
for level in &bids {
book.push_maker_level(Side::Buy, level.price, level.size, MARKET_MAKER_ID);
}
for level in &asks {
book.push_maker_level(Side::Sell, level.price, level.size, MARKET_MAKER_ID);
}
book
}
}
fn volume_profile_total() -> f64 {
static TOTAL: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
*TOTAL.get_or_init(|| {
let mut total = 0.0;
for k in 0..390 {
total += intraday_volume(k as f64 / 390.0, MarketStatus::Open);
}
total
})
}
fn inventory_decay() -> f64 {
static DECAY: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
*DECAY.get_or_init(|| mathx::pow(0.5, 1.0 / INVENTORY_HALF_LIFE_TICKS))
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct LiveCurve {
pub d2y: f64,
pub d10y: f64,
pub dcorp: f64,
}
impl LiveCurve {
pub fn dy(&self, point: CurvePoint) -> f64 {
crate::units::percent_to_fraction(match point {
CurvePoint::Treasury2Y => self.d2y,
CurvePoint::Treasury10Y => self.d10y,
CurvePoint::InvestmentGrade => self.dcorp,
})
}
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct RateBook {
pub instruments: Vec<RateInstrument>,
pub ig_spread: f64,
pub last_corporate: f64,
pub closed_since_open: bool,
}
impl RateBook {
pub fn new(mut instruments: Vec<RateInstrument>, economy: &EconomyState) -> Self {
let ig_spread = credit_spread(economy);
for inst in &mut instruments {
inst.marked_yield = curve_yield(inst.spec.point, economy, ig_spread);
}
RateBook {
instruments,
ig_spread,
last_corporate: economy.corporate_bond_yield,
closed_since_open: false,
}
}
pub fn len(&self) -> usize {
self.instruments.len()
}
pub fn is_empty(&self) -> bool {
self.instruments.is_empty()
}
pub fn index_of(&self, ticker: &str) -> Option<usize> {
self.instruments.iter().position(|i| i.spec.ticker == ticker)
}
pub fn remark_credit_spread(&mut self, economy: &EconomyState) {
self.ig_spread = credit_spread(economy);
self.last_corporate = economy.corporate_bond_yield;
}
pub fn sync(&mut self, economy: &EconomyState, carry: bool) {
if economy.corporate_bond_yield != self.last_corporate {
self.ig_spread = credit_spread(economy);
self.last_corporate = economy.corporate_bond_yield;
}
let ig_spread = self.ig_spread;
for inst in &mut self.instruments {
let y = curve_yield(inst.spec.point, economy, ig_spread);
let dy = y - inst.marked_yield;
if dy == 0.0 && !carry {
continue;
}
let carry_yield = if carry { inst.marked_yield } else { 0.0 };
let step = Repricing::new(inst.spec.duration, inst.spec.convexity, dy, carry_yield);
inst.level = step.apply(inst.level);
inst.day_carry += step.carry;
inst.day_duration += step.duration;
inst.day_convexity += step.convexity;
inst.marked_yield = y;
}
}
pub fn open(&mut self, economy: &EconomyState) {
for inst in &mut self.instruments {
inst.previous_close = inst.price;
inst.day_carry = 0.0;
inst.day_duration = 0.0;
inst.day_convexity = 0.0;
}
let carry = self.closed_since_open;
self.sync(economy, carry);
self.closed_since_open = false;
let vix = economy.vix;
for inst in &mut self.instruments {
let print = inst.quoted_mid(vix);
inst.tick_shock = 0.0;
inst.tick_absorbed = 0.0;
inst.price = print;
inst.open = print;
inst.high = print;
inst.low = print;
inst.volume = 0.0;
}
}
pub fn tick(&mut self, time: GameTime, economy: &EconomyState, flows: &[(String, OrderVolume)]) {
self.tick_live(time, economy, None, flows);
}
pub fn tick_live(
&mut self,
time: GameTime,
economy: &EconomyState,
live: Option<LiveCurve>,
flows: &[(String, OrderVolume)],
) {
let status = get_market_status(time);
if status == MarketStatus::Closed {
return;
}
self.sync(economy, false);
let share = intraday_volume(intraday_fraction(time), status) / volume_profile_total();
let decay = inventory_decay();
let vix = economy.vix;
for inst in &mut self.instruments {
inst.tick_repriced = inst.repriced_pending;
inst.repriced_pending = 0.0;
let mark = match live {
Some(curve) => inst.level_at(curve.dy(inst.spec.point)),
None => inst.level,
};
let last_print = inst.price;
let mut print = inst.quoted_mid_at(mark, vix);
let mut traded = 0.0;
let flow = flows
.iter()
.find(|(t, _)| t == inst.spec.ticker)
.map(|(_, v)| *v)
.unwrap_or_default();
if flow.buy > 0.0 || flow.sell > 0.0 {
let mut book = inst.book_at(mark, vix);
let mut delta = 0.0;
for (side, quantity) in [(Side::Buy, flow.buy), (Side::Sell, flow.sell)] {
let result = book.submit(
side,
quantity,
"flow",
SubmitOptions { limit_price: None, post_remainder: false, order_id: None, skip_own: false, house_ids: false },
);
for fill in &result.fills {
traded += fill.quantity;
}
delta += maker_delta_from_fills(&result.fills);
}
inst.maker_inventory += delta;
if traded > 0.0 {
if let Some(p) = book.last_price {
print = p;
}
}
}
let (shock, absorbed) = decompose(last_print, mark, print);
inst.tick_shock = shock;
inst.tick_absorbed = absorbed;
inst.price = print;
inst.high = mathx::max(inst.high, print);
inst.low = mathx::min(inst.low, print);
inst.volume += inst.avg_volume * share + traded;
if inst.maker_inventory != 0.0 {
inst.maker_inventory *= decay;
}
}
}
pub fn remark_now(&mut self, economy: &EconomyState) {
self.sync(economy, false);
let vix = economy.vix;
for inst in &mut self.instruments {
let last = inst.price;
let print = inst.quoted_mid(vix);
inst.price = print;
inst.high = mathx::max(inst.high, print);
inst.low = mathx::min(inst.low, print);
if last > 0.0 && print > 0.0 {
inst.repriced_pending += mathx::log(print / last);
}
}
}
pub fn book_open_repricing(&mut self, before: &[f64]) {
for (inst, &last) in self.instruments.iter_mut().zip(before.iter()) {
if last > 0.0 && inst.price > 0.0 {
inst.repriced_pending += mathx::log(inst.price / last);
}
}
}
pub fn forget_repriced(&mut self, value: f64) {
for inst in &mut self.instruments {
inst.repriced_pending = value;
}
}
pub fn close(&mut self) {
self.closed_since_open = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::economy::{create_initial_economy_state, InitialEconomyOptions};
fn economy() -> EconomyState {
create_initial_economy_state(&InitialEconomyOptions::default())
}
fn book() -> RateBook {
let instruments = RATE_SPECS
.iter()
.map(|s| RateInstrument::new(*s, s.initial_price, s.avg_volume, s.units_outstanding))
.collect();
RateBook::new(instruments, &economy())
}
fn at(hour: i64, minute: i64) -> GameTime {
GameTime { hour, minute, day_of_week: 3 }
}
#[test]
fn a_200bp_rise_prices_the_10_year_at_minus_15_32_per_cent() {
let r = Repricing::new(8.5, 84.0, 0.02, 0.0);
assert_eq!(r.duration, -0.17);
assert!((r.total() - (-0.1532)).abs() < 1e-15, "{}", r.total());
let two = Repricing::new(1.9, 4.6, 0.02, 0.0).total();
assert!((two - (-0.03708)).abs() < 1e-15, "{two}");
let ig = Repricing::new(7.0, 100.0, 0.02, 0.0).total();
assert!((ig - (-0.12)).abs() < 1e-15, "{ig}");
}
#[test]
fn the_quadratic_is_never_priced_past_its_turning_point() {
let at_bound = Repricing::new(8.5, 84.0, 8.5 / 84.0, 0.0).total();
let beyond = Repricing::new(8.5, 84.0, 0.30, 0.0).total();
assert_eq!(at_bound, beyond);
let fall = Repricing::new(8.5, 84.0, -0.30, 0.0).total();
assert!(fall > 2.5);
}
#[test]
fn an_unchanged_curve_leaves_every_level_alone_inside_a_day() {
let e = economy();
let mut b = book();
b.open(&e);
let levels: Vec<f64> = b.instruments.iter().map(|i| i.level).collect();
for m in 0..390 {
b.tick(at(9 + (30 + m) / 60, (30 + m) % 60), &e, &[]);
}
for (inst, before) in b.instruments.iter().zip(levels) {
assert_eq!(inst.level, before);
assert_eq!(inst.price, before, "an untraded print is the level");
}
}
#[test]
fn the_first_open_accrues_no_carry_and_later_opens_accrue_one_day() {
let e = economy();
let mut b = book();
b.open(&e);
assert_eq!(b.instruments[1].level, 100.0);
b.close();
b.open(&e);
let y = crate::units::percent_to_fraction(e.treasury_yield_10y);
assert_eq!(b.instruments[1].level, 100.0 * (1.0 + y / 252.0));
let once = b.instruments[1].level;
b.open(&e);
assert_eq!(b.instruments[1].level, once);
}
#[test]
fn a_yield_move_reprices_on_the_next_open_by_the_formula() {
let mut e = economy();
let mut b = book();
b.open(&e);
b.close();
let y0 = crate::units::percent_to_fraction(e.treasury_yield_10y);
e.treasury_yield_10y += 2.0;
b.open(&e);
let y1 = crate::units::percent_to_fraction(e.treasury_yield_10y);
let expected = Repricing::new(8.5, 84.0, y1 - y0, y0).apply(100.0);
assert_eq!(b.instruments[1].level, expected);
assert_eq!(b.instruments[1].price, expected);
assert!((expected / 100.0 - 1.0 - (y0 / 252.0 - 0.1532)).abs() < 1e-9);
}
#[test]
fn the_corporate_index_follows_the_10_year_and_re_marks_on_a_corporate_move() {
let mut e = economy();
let mut b = book();
let spread = b.ig_spread;
b.open(&e);
e.treasury_yield_10y += 0.10;
b.sync(&e, false);
let ig = &b.instruments[2];
assert_eq!(b.ig_spread, spread);
assert_eq!(ig.marked_yield, crate::units::percent_to_fraction(e.treasury_yield_10y) + spread);
e.corporate_bond_yield += 2.0;
b.sync(&e, false);
assert_eq!(b.ig_spread, credit_spread(&e));
assert!((b.instruments[2].marked_yield
- crate::units::percent_to_fraction(e.corporate_bond_yield)).abs() < 1e-15);
}
#[test]
fn a_buy_moves_the_print_up_and_the_impact_decays() {
let e = economy();
let mut b = book();
b.open(&e);
let level = b.instruments[1].level;
let flow = vec![("UST10Y".to_string(), OrderVolume { buy: 200_000.0, sell: 0.0 })];
b.tick(at(9, 30), &e, &flow);
let inst = &b.instruments[1];
assert!(inst.maker_inventory < 0.0, "the maker sold");
assert!(inst.price > level, "the print is the last fill, above the level");
b.tick(at(9, 31), &e, &[]);
let skewed = b.instruments[1].price;
assert!(skewed > level, "quotes skew up after the maker went short");
for m in 0..300 {
b.tick(at(9 + (32 + m) / 60, (32 + m) % 60), &e, &[]);
}
let later = b.instruments[1].price;
assert!(later > level && later < skewed, "the skew decays toward the level");
assert_eq!(b.instruments[1].level, level, "flow never moves the level");
}
#[test]
fn a_closed_market_does_nothing() {
let e = economy();
let mut b = book();
b.open(&e);
let before = b.clone();
let flow = vec![("UST2Y".to_string(), OrderVolume { buy: 1e6, sell: 0.0 })];
b.tick(at(3, 0), &e, &flow);
assert_eq!(b, before);
}
#[test]
fn a_session_prints_about_one_days_volume() {
let e = economy();
let mut b = book();
b.open(&e);
for m in 0..390 {
b.tick(at(9 + (30 + m) / 60, (30 + m) % 60), &e, &[]);
}
let inst = &b.instruments[0];
assert!((inst.volume / inst.avg_volume - 1.0).abs() < 1e-9, "{}", inst.volume);
}
#[test]
fn the_book_quotes_one_cent_wide_around_a_level_near_100() {
let e = economy();
let mut b = book();
b.open(&e);
let spread_at = |i: usize, vix: f64| {
let book = b.instruments[i].book(vix);
assert_eq!(book.bids.len(), 10);
assert_eq!(book.asks.len(), 10);
book.best_ask().unwrap() - book.best_bid().unwrap()
};
for (i, calm_to) in [(0, 34.9), (1, 34.9), (2, 22.4)] {
for vix in [10.0, 15.0, 20.0, calm_to] {
assert!((spread_at(i, vix) - 0.01).abs() < 1e-9, "{i} at {vix}");
}
assert!((spread_at(i, 60.0) - 0.02).abs() < 1e-9, "{i} at 60");
}
}
#[test]
fn the_close_remark_prices_the_same_close_and_the_open_adds_only_carry() {
let e0 = economy();
let mut b = book();
b.open(&e0);
b.tick(at(9, 30), &e0, &[]);
let before: Vec<(f64, f64, f64)> =
b.instruments.iter().map(|i| (i.level, i.marked_yield, i.price)).collect();
b.close();
let mut e1 = e0.clone();
e1.treasury_yield_2y += 0.07;
e1.treasury_yield_10y -= 0.12;
e1.corporate_bond_yield += 0.09;
b.remark_now(&e1);
let spread = credit_spread(&e1);
for (inst, (level, y, last)) in b.instruments.iter().zip(before.iter()) {
let y1 = curve_yield(inst.spec.point, &e1, spread);
let expected = Repricing::new(inst.spec.duration, inst.spec.convexity, y1 - y, 0.0)
.apply(*level);
assert_eq!(inst.level, expected, "{}", inst.spec.ticker);
assert_eq!(inst.marked_yield, y1);
assert_eq!(inst.price, inst.level, "untraded, the print is the level");
assert_eq!(inst.repriced_pending, mathx::log(inst.price / last));
}
let closes: Vec<f64> = b.instruments.iter().map(|i| i.price).collect();
let marks: Vec<(f64, f64)> = b.instruments.iter().map(|i| (i.level, i.marked_yield)).collect();
b.open(&e1);
b.book_open_repricing(&closes);
for (inst, (level, y)) in b.instruments.iter().zip(marks.iter()) {
assert_eq!(inst.level, Repricing::new(inst.spec.duration, inst.spec.convexity, 0.0, *y)
.apply(*level), "{}: the open is the carry alone", inst.spec.ticker);
assert_eq!(inst.day_duration, 0.0);
}
let pending: Vec<f64> = b.instruments.iter().map(|i| i.repriced_pending).collect();
b.tick(at(9, 30), &e1, &[]);
for (inst, (p, (_, _, last))) in b.instruments.iter().zip(pending.iter().zip(before.iter())) {
assert_eq!(inst.tick_repriced, *p);
assert_eq!(inst.repriced_pending, 0.0);
assert!((inst.tick_repriced - mathx::log(inst.price / last)).abs() < 1e-15);
}
}
#[test]
fn a_live_mark_prints_around_the_moved_level_and_commits_nothing() {
let e = economy();
let mut plain = book();
plain.open(&e);
let mut live = plain.clone();
let mut none = plain.clone();
plain.tick(at(10, 0), &e, &[]);
none.tick_live(at(10, 0), &e, None, &[]);
assert_eq!(plain, none);
let curve = LiveCurve { d2y: 0.03, d10y: -0.05, dcorp: 0.11 };
live.tick_live(at(10, 0), &e, Some(curve), &[]);
for (a, b) in live.instruments.iter().zip(plain.instruments.iter()) {
assert_eq!(a.level, b.level, "the level is not committed");
assert_eq!(a.marked_yield, b.marked_yield);
let dy = curve.dy(a.spec.point);
assert_eq!(a.price, b.level_at(dy));
assert_ne!(a.price, b.price);
}
assert_eq!(curve.dy(CurvePoint::InvestmentGrade), 0.0011);
}
}