finance-query 3.0.0

A Rust library for querying financial data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use crate::backtesting::config::BacktestConfig;
use crate::backtesting::position::Position;
use crate::backtesting::signal::Signal;
use crate::models::chart::Candle;

use super::BacktestEngine;

/// Unsigned notional of the open position.
///
/// [`Position::current_value`] is negative for shorts, but margin rules are
/// written against the size of the borrowing, not its direction.
#[inline]
pub(super) fn gross_exposure(position: Option<&Position>, price: f64) -> f64 {
    position.map_or(0.0, |pos| pos.quantity * price)
}

/// Capital an entry may commit, including any margin loan.
#[inline]
pub(super) fn entry_buying_power(cash: f64, config: &BacktestConfig) -> f64 {
    cash.max(0.0) * config.max_leverage
}

/// Whether an entry or scale-in tranche fits the buying-power ceiling.
///
/// A long commits its full value plus costs against the ceiling; a short
/// commits its notional but pays only the commission from cash.
#[inline]
pub(super) fn fits_buying_power(
    is_long: bool,
    value: f64,
    commission: f64,
    tax: f64,
    cash: f64,
    buying_power: f64,
) -> bool {
    if is_long {
        value + commission + tax <= buying_power
    } else {
        commission <= cash && value <= buying_power
    }
}

/// Capital a scale-in may add on top of an open position: the unused portion
/// of the exposure ceiling.
///
/// Measured against equity at every leverage, 1.0 included: a short credits its
/// proceeds to cash, so cash overstates what is available.
#[inline]
pub(super) fn add_buying_power(
    cash: f64,
    position: &Position,
    price: f64,
    config: &BacktestConfig,
) -> f64 {
    let equity = cash + position.current_value(price) + position.unreinvested_dividends;
    (equity * config.max_leverage - gross_exposure(Some(position), price)).max(0.0)
}

impl BacktestEngine {
    /// Charge one bar of borrowed-capital cost against cash and the position.
    ///
    /// Shorts pay to borrow the shares; a debit cash balance pays margin
    /// interest. The fee is attributed to the position so it leaves via that
    /// trade's P&L rather than vanishing from cash.
    #[inline]
    pub(super) fn accrue_financing(
        &self,
        position: &mut Option<Position>,
        cash: &mut f64,
        candle: &Candle,
    ) {
        if self.config.short_borrow_rate <= 0.0 && self.config.margin_interest_rate <= 0.0 {
            return;
        }
        let Some(pos) = position.as_mut() else {
            return;
        };

        let per_bar = 1.0 / self.config.bars_per_year;
        let borrow = if pos.is_short() {
            pos.quantity * candle.close * self.config.short_borrow_rate * per_bar
        } else {
            0.0
        };
        let interest = (-*cash).max(0.0) * self.config.margin_interest_rate * per_bar;

        let fee = borrow + interest;
        if fee > 0.0 {
            *cash -= fee;
            pos.accrue_financing_cost(fee);
        }
    }

    /// Liquidation signal when equity has fallen through the maintenance
    /// requirement.
    ///
    /// Equity is recomputed here rather than taken from the bar's opening
    /// snapshot, so the check sees this bar's financing accrual and dividend
    /// credit.
    #[inline]
    pub(super) fn check_margin_call(
        &self,
        position: Option<&Position>,
        cash: f64,
        candle: &Candle,
    ) -> Option<Signal> {
        let pos = position?;
        // A short's exposure grows as price rises while its equity falls, so it
        // can breach the requirement without ever having borrowed cash.
        if self.config.max_leverage <= 1.0 && !pos.is_short() {
            return None;
        }

        let gross = gross_exposure(Some(pos), candle.close);
        if gross <= 0.0 {
            return None;
        }

        let equity = cash + pos.current_value(candle.close) + pos.unreinvested_dividends;
        if equity < gross * self.config.maintenance_margin_pct {
            return Some(
                Signal::exit(candle.timestamp, candle.close)
                    .with_reason("Margin call: equity below maintenance margin requirement"),
            );
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backtesting::engine::fixtures::{
        EnterLongHold, EnterShortHold, EnterShortScaleIn, make_candles,
    };
    use crate::backtesting::result::BacktestResult;
    use crate::models::chart::Dividend;

    fn levered_config(max_leverage: f64) -> BacktestConfig {
        BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .max_leverage(max_leverage)
            .maintenance_margin_pct(0.25)
            .close_at_end(false)
            .build()
            .unwrap()
    }

    fn margin_calls(result: &BacktestResult) -> usize {
        result
            .trades
            .iter()
            .filter(|t| {
                t.exit_signal
                    .reason
                    .as_deref()
                    .is_some_and(|r| r.contains("Margin call"))
            })
            .count()
    }

    fn long_position(quantity: f64, entry_price: f64) -> Position {
        Position::new(
            crate::backtesting::position::PositionSide::Long,
            0,
            entry_price,
            quantity,
            0.0,
            Signal::long(0, entry_price),
        )
    }

    #[test]
    fn test_add_buying_power_is_plain_cash_when_unlevered() {
        let config = BacktestConfig::default();
        let pos = long_position(50.0, 100.0);
        assert_eq!(add_buying_power(5_000.0, &pos, 100.0, &config), 5_000.0);
    }

    #[test]
    fn test_add_buying_power_is_unused_exposure_when_levered() {
        let config = levered_config(2.0);
        let pos = long_position(50.0, 100.0);
        assert_eq!(add_buying_power(5_000.0, &pos, 100.0, &config), 15_000.0);
    }

    #[test]
    fn test_add_buying_power_floors_at_zero_when_fully_committed() {
        let config = levered_config(2.0);
        let pos = long_position(300.0, 100.0);
        assert_eq!(add_buying_power(-20_000.0, &pos, 100.0, &config), 0.0);
    }

    #[test]
    fn test_margin_call_liquidates_a_levered_position_on_a_crash() {
        let candles = make_candles(&[100.0, 100.0, 100.0, 85.0, 85.0]);
        let result = BacktestEngine::new(levered_config(3.0))
            .run("TEST", &candles, EnterLongHold)
            .unwrap();

        assert_eq!(result.trades.len(), 1);
        assert_eq!(margin_calls(&result), 1);
        assert!(result.open_position.is_none());
        assert_eq!(result.trades[0].exit_timestamp, 3);
    }

    #[test]
    fn test_no_margin_call_at_default_leverage() {
        let candles = make_candles(&[100.0, 100.0, 100.0, 85.0, 85.0]);
        let result = BacktestEngine::new(levered_config(1.0))
            .run("TEST", &candles, EnterLongHold)
            .unwrap();

        assert_eq!(margin_calls(&result), 0);
        assert!(result.open_position.is_some());
    }

    #[test]
    fn test_margin_call_liquidates_a_levered_short_when_price_rises() {
        let candles = make_candles(&[100.0, 100.0, 100.0, 115.0, 115.0]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .allow_short(true)
            .max_leverage(3.0)
            .maintenance_margin_pct(0.25)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterShortHold)
            .unwrap();

        assert_eq!(margin_calls(&result), 1);
        assert_eq!(result.trades[0].exit_timestamp, 3);
        assert!(result.open_position.is_none());
    }

    #[test]
    fn test_margin_call_liquidates_an_unlevered_short_when_price_rises() {
        let candles = make_candles(&[100.0, 100.0, 100.0, 180.0, 180.0]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .allow_short(true)
            .maintenance_margin_pct(0.25)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterShortHold)
            .unwrap();

        assert_eq!(margin_calls(&result), 1);
        assert_eq!(result.trades[0].exit_timestamp, 3);
        assert!(result.open_position.is_none());
    }

    #[test]
    fn test_a_stop_that_fills_intrabar_outranks_the_margin_call() {
        let mut candles = make_candles(&[100.0, 100.0, 100.0, 96.0]);
        candles[3].low = 90.0;
        candles[3].close = 85.0;

        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .stop_loss_pct(0.05)
            .max_leverage(3.0)
            .maintenance_margin_pct(0.25)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterLongHold)
            .unwrap();

        assert_eq!(margin_calls(&result), 0);
        assert!((result.trades[0].exit_price - 95.0).abs() < 1e-9);
    }

    #[test]
    fn test_margin_call_fill_pays_exit_slippage() {
        let candles = make_candles(&[100.0, 100.0, 100.0, 85.0, 85.0]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.01)
            .max_leverage(3.0)
            .maintenance_margin_pct(0.25)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterLongHold)
            .unwrap();

        assert_eq!(margin_calls(&result), 1);
        assert!(result.trades[0].exit_price < candles[3].close);
    }

    #[test]
    fn test_margin_call_accounts_for_the_current_bar_dividend() {
        let candles = make_candles(&[100.0, 100.0, 100.0, 85.0, 85.0]);
        let dividends = vec![Dividend {
            timestamp: 3,
            amount: 20.0,
            provider_id: None,
        }];
        let engine = BacktestEngine::new(levered_config(3.0));

        let without = engine.run("TEST", &candles, EnterLongHold).unwrap();
        let with = engine
            .run_with_dividends("TEST", &candles, EnterLongHold, &dividends)
            .unwrap();

        assert_eq!(margin_calls(&without), 1);
        assert_eq!(margin_calls(&with), 0);
    }

    #[test]
    fn test_short_borrow_cost_accrues_and_reduces_pnl() {
        let candles = make_candles(&[100.0; 20]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .allow_short(true)
            .short_borrow_rate(0.10)
            .bars_per_year(252.0)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterShortHold)
            .unwrap();

        assert!(result.metrics.total_financing_cost > 0.0);
        assert!((result.trades[0].pnl + result.trades[0].financing_cost).abs() < 1e-9);
    }

    #[test]
    fn test_margin_interest_accrues_on_a_levered_long() {
        let candles = make_candles(&[100.0; 20]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .max_leverage(2.0)
            .margin_interest_rate(0.10)
            .bars_per_year(252.0)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterLongHold)
            .unwrap();

        assert!(result.metrics.total_financing_cost > 0.0);
        assert!(result.trades[0].pnl < 0.0);
    }

    #[test]
    fn test_max_leverage_used_reports_the_exposure_actually_taken() {
        let candles = make_candles(&[100.0; 20]);

        let flat = BacktestEngine::new(levered_config(2.0))
            .run("TEST", &candles, EnterLongHold)
            .unwrap();
        assert!((flat.max_leverage_used - 2.0).abs() < 0.01);

        let half = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .position_size_pct(0.5)
            .max_leverage(2.0)
            .close_at_end(false)
            .build()
            .unwrap();
        let partial = BacktestEngine::new(half)
            .run("TEST", &candles, EnterLongHold)
            .unwrap();
        assert!((partial.max_leverage_used - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_short_scale_in_cannot_breach_the_leverage_ceiling() {
        let candles = make_candles(&[100.0; 6]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .allow_short(true)
            .max_leverage(2.0)
            .maintenance_margin_pct(0.25)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterShortScaleIn)
            .unwrap();

        let pos = result.open_position.expect("short stays open");
        assert!((pos.quantity - 200.0).abs() < 1e-9);
        assert!(result.max_leverage_used <= 2.0 + 1e-9);
    }

    #[test]
    fn test_short_scale_in_cannot_breach_the_default_ceiling() {
        let candles = make_candles(&[100.0; 6]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .allow_short(true)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterShortScaleIn)
            .unwrap();

        let pos = result.open_position.expect("short stays open");
        assert!((pos.quantity - 100.0).abs() < 1e-9);
        assert!(result.max_leverage_used <= 1.0 + 1e-9);
    }

    #[test]
    fn test_max_leverage_used_accounts_for_the_current_bar_dividend() {
        let candles = make_candles(&[100.0; 6]);
        let dividends = vec![Dividend {
            timestamp: 1,
            amount: 5.0,
            provider_id: None,
        }];
        let engine = BacktestEngine::new(levered_config(2.0));

        let without = engine.run("TEST", &candles, EnterLongHold).unwrap();
        let with = engine
            .run_with_dividends("TEST", &candles, EnterLongHold, &dividends)
            .unwrap();

        assert!((without.max_leverage_used - 2.0).abs() < 0.01);
        assert!(with.max_leverage_used < without.max_leverage_used);
    }

    #[test]
    fn test_financing_cost_counts_a_position_left_open() {
        let candles = make_candles(&[100.0; 20]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .max_leverage(2.0)
            .margin_interest_rate(0.10)
            .bars_per_year(252.0)
            .close_at_end(false)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterLongHold)
            .unwrap();

        let accrued = result
            .open_position
            .as_ref()
            .expect("long stays open")
            .financing_cost_accrued;
        assert!(accrued > 0.0);
        assert_eq!(result.metrics.total_financing_cost, accrued);
    }

    #[test]
    fn test_no_financing_cost_at_default_rates() {
        let candles = make_candles(&[100.0; 20]);
        let config = BacktestConfig::builder()
            .initial_capital(10_000.0)
            .commission_pct(0.0)
            .slippage_pct(0.0)
            .allow_short(true)
            .build()
            .unwrap();
        let result = BacktestEngine::new(config)
            .run("TEST", &candles, EnterShortHold)
            .unwrap();

        assert_eq!(result.metrics.total_financing_cost, 0.0);
    }

    #[test]
    fn test_accounting_invariant_holds_with_financing() {
        let candles = make_candles(&[100.0; 20]);

        for (allow_short, leverage) in [(true, 1.0), (false, 2.0)] {
            let config = BacktestConfig::builder()
                .initial_capital(10_000.0)
                .commission_pct(0.001)
                .allow_short(allow_short)
                .max_leverage(leverage)
                .short_borrow_rate(0.10)
                .margin_interest_rate(0.10)
                .close_at_end(true)
                .build()
                .unwrap();
            let engine = BacktestEngine::new(config);
            let result = if allow_short {
                engine.run("TEST", &candles, EnterShortHold).unwrap()
            } else {
                engine.run("TEST", &candles, EnterLongHold).unwrap()
            };

            let sum_pnl: f64 = result.trades.iter().map(|t| t.pnl).sum();
            let expected = 10_000.0 + sum_pnl;
            assert!(
                (result.final_equity - expected).abs() < 1e-6,
                "final_equity {:.6} != initial + sum(pnl) {expected:.6}",
                result.final_equity,
            );
        }
    }
}