rsRustPrimer
< Back to module

Collections

Running project · riskforge

Project: a multi-counterparty portfolio

A bank does not have one counterparty but hundreds, each with its netting set. So we create a Portfolio that files trades by counterparty: a HashMap<String, NettingSet>. Adding a trade means finding (or creating) the right netting set, which is exactly the job of the entry API.

src/portfolio.rs
use std::collections::{BTreeMap, HashMap};
#[derive(Debug)]
pub struct NettingSet {
pub counterparty: String,
mtms: Vec<f64>,
}
impl NettingSet {
pub fn new(counterparty: &str) -> Self {
Self { counterparty: counterparty.to_string(), mtms: Vec::new() }
}
pub fn add(&mut self, mtm: f64) {
self.mtms.push(mtm);
}
pub fn net_exposure(&self) -> f64 {
let mut total = 0.0;
for mtm in &self.mtms {
total += mtm;
}
total.max(0.0)
}
}
#[derive(Debug, Default)]
pub struct Portfolio {
netting_sets: HashMap<String, NettingSet>,
}
impl Portfolio {
pub fn add(&mut self, counterparty: &str, mtm: f64) {
self.netting_sets
.entry(counterparty.to_string())
.or_insert(NettingSet::new(counterparty))
.add(mtm);
}
/// Exposition nette par contrepartie, triée par nom.
pub fn exposures(&self) -> BTreeMap<String, f64> {
let mut result = BTreeMap::new();
for (name, set) in &self.netting_sets {
result.insert(name.clone(), set.net_exposure());
}
result
}
}
fn main() {
let mut portfolio = Portfolio::default();
portfolio.add("ACME", 10_000.0);
portfolio.add("Globex", -2_000.0);
portfolio.add("ACME", -4_000.0);
println!("{:?}", portfolio.exposures()); // {"ACME": 6000.0, "Globex": 0.0}
}
A simplified version (MtMs instead of real trades) to focus on the HashMap. In the riskforge repository, the Portfolio files the real Trade values from the previous step.

#[derive(Default)] generates a Portfolio::default() with an empty map, without writing a new. And exposures returns a BTreeMap so the report always comes out in the same order: essential to compare two runs or to write tests.

Your turn

Add total_exposure, which sums the net exposures of every counterparty. It is the first number a risk manager looks at.

src/main.rs
use std::collections::HashMap;
#[derive(Default)]
struct Portfolio {
net_mtm: HashMap<String, f64>,
}
impl Portfolio {
fn add(&mut self, counterparty: &str, mtm: f64) {
*self.net_mtm.entry(counterparty.to_string()).or_insert(0.0) += mtm;
}
// ajoute total_exposure ici
}
fn main() {
let mut portfolio = Portfolio::default();
portfolio.add("ACME", 10_000.0);
portfolio.add("Globex", -2_000.0);
portfolio.add("ACME", -4_000.0);
portfolio.add("Initech", 1_500.0);
println!("{}", portfolio.total_exposure()); // 7500
}