Skip to main content

rungbot_backtest/
lib.rs

1//! `rungbot-backtest` — the ladder replayed over history.
2//!
3//! Four backtests and a set of historical replays, all pure computation: price history
4//! and a starting book go in, a report comes out. Reading caches and fetching candles is
5//! the CLI's job (`rungbot backtest ...`).
6//!
7//! * [`invariants`] — scripted price paths through the live ladder, asserting its rules.
8//! * [`window`] — the ladder *as configured* over a trailing window of real prices, with
9//!   dollar bookkeeping, per-pair minimum notional and rollback of skipped trades.
10//! * [`sweep`] — A/B variants of the ladder over the same window and book.
11//! * [`monthly`] — several windows plus the sweep and per-coin band probes, rolled into
12//!   one verdict and an expectation file a divergence check can steer against.
13//! * [`replay`] — cycle studies: bull-confirmation replays, cycle-top anatomy, the bull
14//!   sell policy over past tops, current market microstate.
15//!
16//! The report formats are a contract. The monthly verdict reads the window and sweep
17//! reports back with patterns, so every line is produced with Python's exact number
18//! formatting ([`py`]) and pinned by golden tests against the reference implementation.
19
20#![forbid(unsafe_code)]
21#![deny(clippy::all)]
22
23pub mod exact;
24pub mod invariants;
25pub mod monthly;
26pub mod py;
27pub mod replay;
28pub mod sweep;
29pub mod window;
30
31use py::Py;
32
33/// Hourly or daily prices per coin, `[(epoch_seconds, price)]`, in file order.
34///
35/// This is the shape of the window cache (`bt-hist-{days}d.json`): a JSON object of
36/// `symbol -> [[ts, price], ...]`. Order matters — the first coin's timestamps are the
37/// replay's clock, exactly as in the reference.
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct History(pub Vec<(String, Vec<(i64, f64)>)>);
40
41impl History {
42    pub fn parse(text: &str) -> Result<History, String> {
43        let v = py::loads(text)?;
44        let mut out = Vec::new();
45        for (k, pts) in v.items() {
46            let sym = k
47                .as_str()
48                .ok_or("history keys must be symbols")?
49                .to_string();
50            let mut series = Vec::new();
51            for p in pts.as_list() {
52                let pair = p.as_list();
53                if pair.len() < 2 {
54                    return Err(format!("{sym}: each point must be [ts, price]"));
55                }
56                let t = pair[0].as_f64().ok_or("timestamp must be a number")?;
57                let px = pair[1].as_f64().ok_or("price must be a number")?;
58                series.push((t as i64, px));
59            }
60            out.push((sym, series));
61        }
62        if out.is_empty() {
63            return Err("history has no coins".into());
64        }
65        Ok(History(out))
66    }
67
68    pub fn to_json(&self) -> String {
69        Py::Dict(
70            self.0
71                .iter()
72                .map(|(s, pts)| {
73                    (
74                        Py::from(s.as_str()),
75                        Py::List(
76                            pts.iter()
77                                .map(|(t, p)| Py::List(vec![Py::Int(*t), Py::Float(*p)]))
78                                .collect(),
79                        ),
80                    )
81                })
82                .collect(),
83        )
84        .json(None)
85    }
86
87    pub fn get(&self, sym: &str) -> Option<&Vec<(i64, f64)>> {
88        self.0.iter().find(|(s, _)| s == sym).map(|(_, v)| v)
89    }
90}
91
92/// An ordered `name -> number` map, as the book file stores it.
93pub type Named = Vec<(String, f64)>;
94
95pub fn named_get(m: &Named, k: &str) -> Option<f64> {
96    m.iter().find(|(n, _)| n == k).map(|(_, v)| *v)
97}
98
99pub fn named_set(m: &mut Named, k: &str, v: f64) {
100    match m.iter_mut().find(|(n, _)| n == k) {
101        Some(slot) => slot.1 = v,
102        None => m.push((k.to_string(), v)),
103    }
104}
105
106/// The starting book: holdings per coin, free stable per venue, each pair's minimum
107/// order notional, and how many coins share each venue's stable bag.
108///
109/// Same shape as `bt-book.json`, which the window run writes and the sweep reads, so
110/// both replay the identical book.
111#[derive(Debug, Clone, Default, PartialEq)]
112pub struct Book {
113    pub held: Named,
114    pub stable: Named,
115    pub min_notional: Named,
116    pub counts: Vec<(String, i64)>,
117}
118
119fn named_from(v: Option<&Py>) -> Result<Named, String> {
120    let mut out = Vec::new();
121    if let Some(v) = v {
122        for (k, x) in v.items() {
123            let k = k.as_str().ok_or("book keys must be strings")?.to_string();
124            let x = x
125                .as_f64()
126                .ok_or_else(|| format!("book value for {k} is not a number"))?;
127            out.push((k, x));
128        }
129    }
130    Ok(out)
131}
132
133impl Book {
134    pub fn parse(text: &str) -> Result<Book, String> {
135        let v = py::loads(text)?;
136        let counts = named_from(v.get("counts"))?
137            .into_iter()
138            .map(|(k, c)| (k, c as i64))
139            .collect();
140        Ok(Book {
141            held: named_from(v.get("held"))?,
142            stable: named_from(v.get("stable"))?,
143            min_notional: named_from(v.get("min_notional"))?,
144            counts,
145        })
146    }
147
148    pub fn to_py(&self) -> Py {
149        let m = |n: &Named| {
150            Py::Dict(
151                n.iter()
152                    .map(|(k, v)| (Py::from(k.as_str()), Py::Float(*v)))
153                    .collect(),
154            )
155        };
156        Py::Dict(vec![
157            ("held".into(), m(&self.held)),
158            ("stable".into(), m(&self.stable)),
159            ("min_notional".into(), m(&self.min_notional)),
160            (
161                "counts".into(),
162                Py::Dict(
163                    self.counts
164                        .iter()
165                        .map(|(k, v)| (Py::from(k.as_str()), Py::Int(*v)))
166                        .collect(),
167                ),
168            ),
169        ])
170    }
171
172    pub fn to_json(&self) -> String {
173        self.to_py().json(None)
174    }
175}
176
177/// How a configured cost basis prints. A whole number was written as one.
178pub fn entry_text(v: Option<f64>) -> String {
179    match v {
180        None => "None".into(),
181        Some(x) if x.fract() == 0.0 && x.abs() < 1e16 => format!("{}", x as i64),
182        Some(x) => py::repr(x),
183    }
184}