Why Rust for Finance?
When Python is too slow and C++ is too dangerous, Rust is the sweet spot for high-performance financial computing.
Speed: Python vs Rust
Python is brilliant for prototyping but it is an interpreted language. For number-crunching at scale — pricing millions of options, running Monte Carlo simulations, processing tick data — Python can be painfully slow.
# Python — 1 million compound interest calculations
# ~2.1 seconds on a modern machine
import time
start = time.time()
for _ in range(1_000_000):
result = 10000 * (1 + 0.07 / 12) ** (12 * 10)
print(f"Python: {time.time() - start:.3f}s")
# Rust — same calculation, same machine
# ~0.003 seconds (700x faster)Rust compiles to native machine code. For pure computation it is typically 100x to 1000x faster than Python. In finance, that means you can backtest 10 years of tick data in seconds instead of hours.
Memory Safety Without a Garbage Collector
C and C++ are fast but infamous for memory bugs — buffer overflows, use-after-free, dangling pointers. These bugs cause crashes and security vulnerabilities. In a trading system, a segfault can mean real money lost.
Rust eliminates these bugs at compile time through its ownership system. If your code compiles, it is memory-safe. No garbage collector, no runtime overhead, no surprises.
When to Use Rust vs Python
| Use Case | Python | Rust |
|---|---|---|
| Quick analysis / notebooks | Best | Overkill |
| Data pipelines | Good | Better at scale |
| Monte Carlo (millions of paths) | Slow | Excellent |
| Real-time pricing engine | Too slow | Ideal |
| Tick data processing | Possible | Much faster |
| Machine learning | Best (sklearn, torch) | Growing (burn, candle) |
Installing Rust
The official installer is rustup. Run this in your terminal:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustc --versionHello World
Create a file called main.rs:
fn main() {
println!("Hello, financial world!");
}Compile and run: rustc main.rs && ./main
Variables, Types, and Functions
Rust is statically typed. Variables are immutable by default — you need mut to make them mutable. Here is a financial example:
fn main() {
// Immutable by default
let ticker = "AAPL";
let price: f64 = 178.52;
let shares: u32 = 100;
// Mutable variable
let mut portfolio_value: f64 = price * shares as f64;
println!("{}: {} shares @ ${:.2} = ${:.2}", ticker, shares, price, portfolio_value);
// Update
let new_price: f64 = 182.10;
portfolio_value = new_price * shares as f64;
println!("Updated value: ${:.2}", portfolio_value);
println!("P&L: ${:.2}", portfolio_value - (price * shares as f64));
}Cargo: The Rust Build System
Real Rust projects use Cargo, which handles building, dependencies, and testing:
cargo new finance_calc
cd finance_calc
cargo runThis creates a new project with a Cargo.toml (like package.json) and a src/main.rs file.
First Financial Calculation: Compound Interest
Let us write something useful. Replace the contents of src/main.rs with this compound interest calculator:
fn compound_interest(principal: f64, rate: f64, years: u32, compounds_per_year: u32) -> f64 {
let n = compounds_per_year as f64;
let t = years as f64;
principal * (1.0 + rate / n).powf(n * t)
}
fn main() {
let principal = 10_000.0;
let annual_rate = 0.07; // 7%
let years = 10;
// Compare compounding frequencies
let frequencies = [
("Annually", 1),
("Quarterly", 4),
("Monthly", 12),
("Daily", 365),
];
println!("Compound Interest Calculator");
println!("Principal: ${:.2}", principal);
println!("Annual rate: {:.1}%", annual_rate * 100.0);
println!("Duration: {} years
", years);
for (label, freq) in &frequencies {
let result = compound_interest(principal, annual_rate, years, *freq);
let growth = result - principal;
println!("{:<12} -> ${:.2} (growth: ${:.2})", label, result, growth);
}
}Run it with cargo run. You will see how compounding frequency affects growth — daily compounding yields about $40 more than annual over 10 years at 7%.
Try It Yourself
- Add continuous compounding:
principal * (rate * t).exp() - Add a function that calculates how many years to double your money at a given rate.
- Handle edge cases: what if rate is negative or years is 0?