CH
CalcHub
Back to Guides
Beginner

Why Rust for Finance?

Python is fantastic for research and prototyping, but when you need raw speed โ€” processing millions of data points per second, running a live trading system, or building infrastructure โ€” Rust is increasingly the language of choice.

Rust vs Python: When to Use Each

Use Python for research, exploration, and prototyping. Use Rust for production systems where speed, reliability, and safety matter. Many quant firms write strategies in Python first, then rewrite the proven ones in Rust or C++ for production.

Why Rust?

  • Speed โ€” Close to C/C++, orders of magnitude faster than Python
  • Memory safety โ€” The compiler prevents null pointer dereferences, data races, and memory leaks
  • No garbage collector โ€” Predictable performance with no GC pauses (critical for HFT)
  • Concurrency โ€” Fearless concurrency โ€” the type system prevents data races at compile time
  • Growing adoption โ€” Used by crypto exchanges (Solana), HFT firms, and fintech companies

Installing Rust

# Install Rust using rustup (the official installer) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Verify installation rustc --version cargo --version # Cargo is Rust's package manager and build tool # It's like pip + setuptools combined

Hello World and Basic Syntax

// Create a new project: cargo new finance_app // This creates a directory with src/main.rs and Cargo.toml fn main() {{ // Variables are immutable by default let price = 150.50; let ticker = "AAPL"; // Use 'mut' for mutable variables let mut balance = 10000.0; balance -= price; println!("Bought 1 share of {{}} at ${{:.2}}", ticker, price); println!("Remaining balance: ${{:.2}}", balance); }}

Types and Functions

// Rust is strongly typed โ€” the compiler catches type errors fn calculate_return(buy_price: f64, sell_price: f64) -> f64 {{ (sell_price - buy_price) / buy_price * 100.0 }} fn main() {{ let buy = 150.0; let sell = 165.0; let ret = calculate_return(buy, sell); println!("Return: {{:.2}}%", ret);  // Return: 10.00% // Common types: // f64  โ€” 64-bit float (default for decimal numbers) // f32  โ€” 32-bit float (less precision, less memory) // i32  โ€” 32-bit integer // i64  โ€” 64-bit integer // usize โ€” unsigned integer (for array indices) // bool  โ€” true or false // String / &str โ€” text }}

Structs: Custom Data Types

// Structs are like Python classes but without inheritance struct StockBar {{ date: String, open: f64, high: f64, low: f64, close: f64, volume: u64, }} impl StockBar {{ // Method: calculate the bar's range fn range(&self) -> f64 {{         self.high - self.low }}     // Method: is this a bullish bar? fn is_bullish(&self) -> bool {{      self.close > self.open }} }} fn main() {{  let bar = StockBar {{      date: "2024-01-15".to_string(), open: 185.50, high: 188.20, low: 184.80, close: 187.90, volume: 52_000_000, }};    println!("Date: {{}}", bar.date); println!("Range: ${{:.2}}", bar.range()); println!("Bullish: {{}}", bar.is_bullish()); }}

Vectors: Dynamic Arrays

fn main() {{ // Vectors are like Python lists but typed let prices: Vec<f64> = vec![100.0, 102.5, 101.0, 105.0, 103.5]; // Calculate returns using iterators let returns: Vec<f64> = prices .windows(2) .map(|w| (w[1] - w[0]) / w[0] * 100.0) .collect(); println!("Prices: {{:?}}", prices); println!("Returns: {{:.2?}}", returns); // Mean return let mean: f64 = returns.iter().sum::<f64>() / returns.len() as f64; println!("Mean return: {{:.2}}%", mean); }}

Cargo: Adding Dependencies

# Cargo.toml โ€” like requirements.txt in Python [package] name = "finance_app" version = "0.1.0" edition = "2021" [dependencies] csv = "1.3"           # Reading CSV files serde = {{ version = "1.0", features = ["derive"] }}  # Serialisation chrono = "0.4"        # Date/time handling # Run: cargo build  (downloads and compiles dependencies) # Run: cargo run    (build + execute)