rsRustPrimer
< Back to module

Language basics

Running project · riskforge

Project: positive exposure

We have every building block for a first version of riskforge. For each simulated scenario, the contract has an MtM. Exposure is the positive part of that MtM: if the value is negative, a counterparty default costs us nothing.

src/main.rs
const SCENARIOS: usize = 5;
fn exposure(mtm: f64) -> f64 {
if mtm > 0.0 { mtm } else { 0.0 }
}
fn main() {
// MtM du contrat dans 5 scénarios de marché, à une date future
let mtms: [f64; SCENARIOS] = [1_200.0, -300.0, 450.0, 0.0, -800.0];
let mut total = 0.0;
for mtm in mtms {
total += exposure(mtm);
}
let expected_exposure = total / SCENARIOS as f64;
println!("EE = {expected_exposure:.2}");
}
EE = (1200 + 0 + 450 + 0 + 0) / 5 = 330. Negative scenarios count as zero, but they still count in the average.

A deliberate limitation: the array has a fixed size and the logic lives in main. In the next module we will pass scenarios by reference to dedicated functions, which will introduce ownership.

Your turn

Add the maximum exposure (the highest exposure across scenarios) and print it next to EE.

src/main.rs
fn exposure(mtm: f64) -> f64 {
mtm.max(0.0)
}
fn main() {
let mtms = [1_200.0, -300.0, 450.0, 0.0, -800.0];
let mut total = 0.0;
for mtm in mtms {
total += exposure(mtm);
}
println!("EE = {:.2}", total / mtms.len() as f64);
// exposition maximale ici
}