<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arsène Ducrocq on Medium]]></title>
        <description><![CDATA[Stories by Arsène Ducrocq on Medium]]></description>
        <link>https://medium.com/@ducrocqarsene?source=rss-2f14e3d80313------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UDtD1onSG8_UI4pItAXSjg.png</url>
            <title>Stories by Arsène Ducrocq on Medium</title>
            <link>https://medium.com/@ducrocqarsene?source=rss-2f14e3d80313------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:46:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ducrocqarsene/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pricing binary contract using Vanilla-Option — Engine in Rust]]></title>
            <link>https://medium.com/@ducrocqarsene/pricing-binary-contract-using-vanilla-option-engine-in-rust-8c405934da79?source=rss-2f14e3d80313------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c405934da79</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[binary-options]]></category>
            <category><![CDATA[quant]]></category>
            <dc:creator><![CDATA[Arsène Ducrocq]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 18:09:21 GMT</pubDate>
            <atom:updated>2026-10-01T18:09:21.237Z</atom:updated>
            <content:encoded><![CDATA[<p>Since 2022, the emergence of prediction markets such as Polymarket has led to an explosion in the popularity of binary contracts. These contracts cover political, sporting, and cultural events.</p><p>Unlike financial options, there is no real “magic formula” or established framework we can rely on to price these events. Instead, we often have to use deep learning models trained on data that can be difficult to acquire or process.</p><p>However, some contracts, particularly those based on financial market predictions, can be priced using traditional techniques. This is what we are going to explore in this article.</p><p><strong>Table of Contents</strong></p><ol><li>Toy Example with Brownian Motion</li><li>Deriving Risk-Neutral Prices from Deribit Vanilla Options</li></ol><p>Before starting with the first simple example, I would like you to take a moment to think about how you would assign a fair price to a contract such as <strong>BTC &gt; $80,000 in two months</strong>.</p><p>The problem here lies in the word “fair”. What does it actually mean? How can we say that an observed price contains absolutely all the information currently available in the market?</p><p>For example, suppose I tell you today that a stock is undervalued and should rise by 15% this year. Should the option price take my estimate into account? If so, what should we do if someone else believes the stock will rise by 40%, while another trader thinks it will fall by 5%?</p><p>To address these questions, financial mathematics distinguishes between the probability measure <strong>P</strong> and the <strong>risk-neutral probability measure Q</strong>. The latter allows us to replace subjective expected returns, whether they are 15% or -5%, with the risk-free rate when pricing derivatives under the appropriate assumptions.</p><p>The intuition behind this change of measure is that, in an idealized market with no arbitrage, assets cannot systematically offer returns that violate the pricing relationships implied by the risk-free rate and the available trading opportunities.</p><p>If we look more closely at these assumptions, we realize that they do not imply that every market participant has access to the same information or processes it in the same way. These asymmetries, whether in acquiring or processing information, are among the factors that sophisticated firms such as Jane Street or Two Sigma may exploit.</p><p>The important point is that this framework gives us a consistent way to price a contract. We will therefore use it throughout this article. However, it is important to remember that <strong>risk-neutral pricing is not a predictive model</strong>. Its purpose is not to tell us what will happen, but to assign a price to uncertainty.</p><h3>1. Toy Example with Brownian Motion in Rust</h3><p>The stochastic differential equation (SDE) for Geometric Brownian Motion (GBM) is:</p><pre>under P<br>dSt = St*µ*dt + St*σ*dWt<br>under risk-neutral Q<br>dSt = St*r*dt + St*σ*dWt<br><br>r = risk free rate</pre><p>To assign a fair price to this type of contract, the general process is:</p><p><strong>Model (SDE, Neural Network, etc.) → Monte Carlo → Extract Price</strong></p><p>Here, I have chosen GBM as our model. Readers interested in exploring other approaches can reproduce this example using the Merton jump-diffusion model, which adds a jump term (dJ_t) to account for sudden price movements.</p><p>In this example, we will price the contract:</p><p><strong>“BTC &gt; $80,000 in one year”</strong></p><p>The current Bitcoin price is $70,000, the risk-free rate is 4%, and volatility is 20%.</p><p>Code:</p><pre>use rand;<br>use rand_distr::{Distribution, Normal};<br><br>fn gbm(s0: f64, mu: f64, sigma: f64, T: f64, step: f64) -&gt; f64 {<br>    let mut rn = rand::rng();<br>    let norm = Normal::new(0.0, 1.0).unwrap();<br>    let mut st = s0;<br>    let n_steps = step as usize;<br>    let dt = T / n_steps as f64;<br>    <br>    for _ in 0..n_steps {<br>        let dWt = norm.sample(&amp;mut rn);<br>        st *= ((mu - 0.5 * sigma.powi(2)) * dt<br>            + sigma * dWt * dt.sqrt()).exp();<br>    }<br>    st<br>}<br>fn price_bitcoin() {<br>    let s0 = 70000.;<br>    let sigma = 0.2; // 20%<br>    let rf = 0.04; // 4% risk free rate<br>    let T = 1.0; // time in years<br>    let step = 252.; <br>    let N = 100000;<br>    let mut terminal_price = Vec::with_capacity(N);<br>    for _ in 0..N {<br>        terminal_price.push(gbm(s0, rf, sigma, T, step))<br>    }<br>    // Pricing part<br>    // BTC &gt; 80000<br>    let upper_condition = 80000.;<br>    let mut fair_price = 0.0;<br>    <br>    for t_price in terminal_price.into_iter() {<br>        fair_price += (t_price &gt; upper_condition) as i32 as f64; <br>    }<br>    let fair_price = (fair_price / N as f64)  * (-rf*T as f64).exp();<br>    println!(&quot;Estimated price of BTC &gt; 80,000 in one year: {fair_price}&quot;);<br>}</pre><p>I found a value of ~0.26$ for this contract, interested readers can check this result by running the code above.</p><h3>2.1 Pricing binary option contract using Vanilla Option</h3><p>In the model above, we had to choose the volatility parameter ourselves. In a real market, doing this naively would expose us to arbitrage by other traders and could lead to persistent losses.</p><p>To avoid this, whenever market data is available, it is preferable to use vanilla option prices to derive the price of an exotic option, such as a binary contract.</p><p>In this section, we will look at two types of binary contracts:</p><blockquote><strong><em>Case A: Asset &gt; X at date DDMMYYYY</em></strong><em> (e.g. BTC &gt; $60,000 on November 15, 2026)</em></blockquote><p>This is the simplest case. We can use the prices of European calls to infer the risk-neutral probability that the underlying will finish above a given strike. In the Black-Scholes model, this probability is N(d_2).</p><p>For example, to price a contract paying out if BTC is above $60,000 on November 15, 2026, we can use the implied volatility of the corresponding call and calculate the risk-neutral probability at that strike and maturity.</p><blockquote><strong><em>Case B: Asset A &gt; Asset B at date DDMMYYYY</em></strong><em> (e.g. BTC has a higher return than Gold in 2026)</em></blockquote><p>These contracts are more complicated to price because they require us to model the distribution of the two assets. We can calibrate the marginal dynamics to current vanilla option prices, then use a Monte Carlo simulation to estimate the probability of the event.</p><p>The problem becomes more complex when the two assets are dependent. We then need to model their joint distribution, for example by introducing a correlation structure. This adds parameters and modeling choices, which can make calibration very difficult (we don’t want to deal with that but I’ll try to do it a in a future article).</p><p>Here is some Python pseudocode to illustrate the idea:</p><pre>def Model(**kwargs) -&gt; float:<br>&quot;&quot;&quot;<br>Can be Heston, GBM, or neural net (VAE, GAN...) that have been calibrated<br>on market volatility surface<br>Return the terminal price or the return for one simulation<br>&quot;&quot;&quot;<br>  pass<br><br>def get_price(A_kwargs, B_kwargs, N=1000) -&gt; float:<br>   condition = lambda a, b: a &gt; b<br>   p = 0.0<br>   for _ in range(N):<br>      a = Model(**A_kwargs)<br>      b = Model(**B_kwargs)<br>      <br>      p += condition(a, b)<br>   <br>  return p / N</pre><p>We first define a model that returns a simulated terminal price or return, depending on what the contract requires. This could be the simple GBM model we saw above, although in practice it is not flexible enough to capture the market volatility smile because it assumes constant volatility.</p><p>We then apply the condition defined by the binary contract to each simulation. By averaging the outcomes across all simulations, we obtain a Monte Carlo estimate of the event probability.</p><h3>2.2 Building the pricing engine</h3><h3>Architecture</h3><p>Before starting to code, it is important to think about the architecture of this kind of engine, the constraints we have, and how to address them efficiently.</p><p>We have two main components: a client responsible for communicating with Deribit and a pricing engine responsible for processing the data and extracting the probabilities.</p><p>I decided to separate them into two different crates. The main reason is reusability: the Deribit client should be independent from the pricing logic, so that I can use it in other trading strategies or engines without having to modify it.</p><p>The architecture will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHBisj58l4Encs6frpToKg.png" /></figure><p>For the communication layer, I chose WebSockets because the goal is to build a real-time engine. Instead of repeatedly requesting prices, we can subscribe to market channels and receive updates as they arrive. All the instruments we need are defined at startup, which keeps subscription management simple for this first implementation.</p><p>We also need to make sure that the client does not interfere with the tasks consuming the data. For this reason, I use a Tokio mpsc channel to forward raw messages from the client to the pricing engine. The client only handles communication with Deribit; the pricing engine is responsible for everything that happens after receiving a message.</p><p>For now, the channel has a single receiver. This is enough for the current project, and it keeps the data flow straightforward.</p><p>There is one last constraint to consider: rebuilding the entire implied volatility surface after every market update would be unnecessarily expensive. Instead, I chose to process the latest known quote for each instrument and rebuild the surface every 10 seconds. This is a trade-off between freshness and computation: we do not need to recalculate the whole surface for every incoming message.</p><p>Another possible approach would be to share prices between tasks using Arc&lt;Mutex&lt;...&gt;&gt; and calculate the surface in a separate thread. However, this would introduce synchronization and locking considerations. Since the current objective does not require an update on every market event, periodic batch processing is a simpler solution.</p><h3>Building the Deribit client</h3><p>We first need to create the client library and define the structures that will allow us to communicate with Deribit.</p><pre>cargo init deribit_client --lib</pre><p>We will need a few dependencies for HTTP requests, WebSocket communication, asynchronous tasks and JSON serialization.</p><pre>[dependencies]<br>reqwest = &quot;0.13.4&quot;<br>tokio-tungstenite = { version = &quot;0.30&quot;, features = [&quot;native-tls&quot;] }<br>serde = { version = &quot;1.0.229&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0.151&quot;<br>tokio = { version = &quot;1.53.1&quot;, features = [&quot;full&quot;] }<br>futures-util = { version = &quot;0.3.28&quot;, features = [&quot;sink&quot;, &quot;std&quot;] }<br>tungstenite = &quot;0.30.0&quot;<br>anyhow = &quot;1.0.104&quot;</pre><p>I use serde to convert JSON messages into Rust structures. For example, here is the structure we need to extract an option quote:</p><pre>use serde::Deserialize;<br><br>#[derive(Debug, Deserialize)]<br>pub struct Quote {<br>   pub timestamp: u64,<br>   pub instrument_name: String,<br>   pub best_ask_price: f64,<br>   pub best_bid_price: f64,<br>   pub best_ask_amount: f64,<br>   pub best_bid_amount: f64<br>}</pre><p>We can now use serde_json::from_str::&lt;Quote&gt;(&amp;str) to parse a message into this structure. The other messages follow the same principle, so I will not include every structure here.</p><p>The next step is to create the client itself:</p><pre>#[derive(Debug)]<br>pub struct DeribitClient {<br>    client: Client,<br>}<br>impl DeribitClient {<br>    pub fn new() -&gt; Result&lt;Self, reqwest::Error&gt; {<br>        let mut headers = HeaderMap::new();<br>        headers.insert(&quot;Content-Type&quot;, &quot;application/json&quot;.parse().unwrap());<br>        let client = Client::builder()<br>                                    .default_headers(headers)<br>                                    .pool_idle_timeout(Some(std::time::Duration::from_secs(30)))<br>                                    .build()?;<br>        Ok(Self {client})<br>    }<br>}</pre><p>We will use REST requests to retrieve the available instruments and the underlying index prices. Once we have this initial information, we can subscribe to the instruments through the WebSocket.</p><p>The WebSocket connection is handled with tokio_tungstenite. The connect_async function returns a stream that we can split into a read and a write half. This allows us to send the subscription request and then continuously read incoming messages.</p><pre>// in impl DeribitClient    <br>pub async fn connect_ws(&amp;self, channels: Vec&lt;String&gt;, id: Option&lt;u64&gt;, sx: Sender&lt;Message&gt;) -&gt; Result&lt;(), anyhow::Error&gt;  {<br>        let method = &quot;public/subscribe&quot;.to_string();<br>        let inner_param = WSsub::new(channels);<br>        let connect_param = DeribitParam::new(method, None, id, inner_param);<br>        <br>        let mut url = DeribitEndpoint::WEBSOCKET.to_str().into_client_request()?;<br>        url.headers_mut().insert(&quot;Content-Type&quot;, &quot;application/json&quot;.parse()?);<br>        <br>        println!(&quot;Try connection with deribit websocket...&quot;);<br>        println!(&quot;Connection info: {url:?}&quot;);<br>        <br>        let (stream, _) = connect_async(url).await?;<br>        let (mut write, mut read) = stream.split();<br>        let params_msg = connect_param.into_message()?;<br>        write.send(params_msg).await?;<br>        <br>        while let Some(msg) = read.next().await {<br>            match msg {<br>                Ok(msg) =&gt; { sx.send(msg).await? },<br>                _ =&gt; {}<br>            }<br>        }<br>        <br>        Ok(())<br>}</pre><p>The channels parameter contains the instruments we want to subscribe to. The sx parameter is the sender side of the Tokio channel. Each message received from Deribit is forwarded to the pricing engine, without applying any pricing logic inside the client.</p><p>This is the main purpose of the separation: the client knows how to retrieve data, but it does not need to know what the engine will do with it.</p><p>We also add two REST methods: one to retrieve the index price and another to retrieve the available option instruments for a given currency. These are used during initialization, before the continuous stream of updates begins.</p><p>Here is the code:</p><pre>pub async fn get_price(&amp;self, instrument_name: &amp;str) -&gt; Result&lt;IndexPriceRoot, anyhow::Error&gt;  {<br>        let url = format!(&quot;{}/public/get_index_price?index_name={}&quot;, DeribitEndpoint::REST.to_str() , instrument_name.to_lowercase());<br>        let r = self.client.get(&amp;url).send().await?;<br>        let text=r.text().await?;<br>        Ok(serde_json::from_str::&lt;IndexPriceRoot&gt;(&amp;text)?)<br>    }<br>pub async fn get_instruments(&amp;self, instrument_name: &amp;str, expired: Option&lt;bool&gt;) -&gt; Result&lt;InstrumentsList, anyhow::Error&gt; {<br>        let expired= expired.unwrap_or(false);<br>        let rest_url = format!(&quot;{}/public/get_instruments?currency={instrument_name}&amp;expired={expired}&amp;kind=option&quot;, DeribitEndpoint::REST.to_str());<br>        <br>        let r = self.client.get(rest_url).send().await?;<br>        let text=r.text().await?;   <br>        Ok(serde_json::from_str::&lt;InstrumentsList&gt;(&amp;text)?)<br>    }</pre><h3>From raw quotes to option prices</h3><p>We now have a way to receive market data, but the messages from Deribit are not yet in the format we want to use in the pricing engine.</p><p>The first step is to convert each quote into a normalized structure containing the information needed for pricing:</p><pre>#[derive(Debug, Default)]<br>pub struct OptionPrice {<br>    pub bid: f64,<br>    pub ask: f64,<br>    pub timestamp: u64,<br>    pub strike: f64,<br>    pub expiration: u64,<br>    pub underlying: String,<br>    pub option_type: OptionType,<br>}</pre><p>The OptionPrice structure contains the bid and ask prices, the timestamp of the quote, and the characteristics of the option. We can then add methods to calculate the mid-price, time to expiration, implied volatility and risk-neutral probability.</p><p>The mid-price is simply the average of the bid and ask:</p><pre>pub fn mid(&amp;self) -&gt; f64 {<br>    (self.bid + self.ask) / 2.0<br>}</pre><p>We also need to calculate the time to expiration. Since the timestamps are expressed in seconds, we subtract the current quote timestamp from the expiration timestamp and then convert the result into the time unit expected by Black-Scholes.</p><pre>pub fn time_to_exp(&amp;self) -&gt; u64 {<br>    if self.expiration &lt; self.timestamp {<br>        return 0;<br>    }<br>  self.expiration - self.timestamp<br>  } // we will normalize in year later</pre><p>The next step is to calculate the implied volatility. This is the volatility parameter that, when plugged into the Black-Scholes formula, gives us the observed market price.</p><p>In other words, we want to find σ such that:</p><p>BS(S,K,σ,T,r)=Pmarket</p><p>Or</p><p>BS(σ) = Pmarket</p><p>Because we can’t change the others four parameters like we want.</p><p>There is no simple closed-form solution for implied volatility, so we use an iterative method. In this implementation, I use Newton’s method, which updates the volatility estimate using the difference between the theoretical and market prices and the option’s vega using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/0*7X4iMzo7gZuDSWk9" /></figure><p>We can write:</p><p>f(σ)= BS(σ) — MarketPrice</p><p>f’(σ) = BS(σ)’ — (MarketPrice)’= Vega</p><p>σ{n+1} = σ{n} — (f(σ)/f’(σ))</p><p>Code:</p><pre>// in impl OptionPrice<br>pub fn get_iv(&amp;self, underlying_price: f64) -&gt; f64 {<br>    let mid = self.mid();<br>    let tau = normalize_timestamp(self.time_to_exp());<br><br>get_black_sholes_iv(<br>        mid,<br>        underlying_price,<br>        self.strike,<br>        tau,<br>        RF,<br>        &amp;self.option_type,<br>    )<br>}<br>// black_sholes.rs <br>pub fn get_black_sholes_iv(option_price: f64, price: f64, strike: f64, tau: f64, rho: f64, option_type: &amp;OptionType) -&gt; f64 {<br>    let mut sigma = 0.2;<br>    let tol=1e-6;<br>    let max_iter = 100;<br>    let mut guess = black_sholes_price(price, strike, sigma, tau, rho, option_type);<br>    let mut delta = guess - option_price;<br>    let mut i = 0;<br>    while delta.abs() &gt; tol &amp;&amp; max_iter &gt; i  {<br>        let v = vega(price, strike, sigma, tau, rho);<br>        sigma -= delta / v;<br>        guess = black_sholes_price(price, strike, sigma, tau, rho, option_type);<br>        delta = guess - option_price;<br>        i+=1;<br>    }<br>    sigma<br>}</pre><p>Once we have the implied volatility, we can calculate the probability associated with the option strike.</p><p>In Black-Scholes, the risk-neutral probability Q(ST&gt;K) is N(d2), N being the cumulative density function of the normal law.</p><p>For a cash-or-nothing binary paying one unit when ST&gt;K, the theoretical price is the discounted probability:</p><p>V=exp(-rT)*N(d2​)</p><pre>pub fn risk_neutral_price(&amp;self, underlying_price: f64) -&gt; f64 {<br>        let tau = normalize_timestamp(self.time_to_exp());<br>        let iv = self.get_iv(underlying_price);<br>        risk_neutral_price(underlying_price, self.strike, iv, tau, RF)<br>    }<br>// black_sholes.rs<br>pub fn risk_neutral_price(price: f64, strike: f64, sigma: f64, tau: f64, rho: f64) -&gt; f64 {<br>    let norm = Normal::new(0.0, 1.0).unwrap();<br>    (-tau*rho).exp()*norm.cdf(d2(price, strike, sigma, tau, rho))<br>}</pre><p>Lastly we want our raw quote to be directly cast into our OptionPrice struct:</p><pre>pub fn from_quote(quote: &amp;Quote) -&gt; Result&lt;Self, anyhow::Error&gt; {<br>        let mut price = OptionPrice::default();<br>        price.ask = quote.best_ask_price;<br>        price.bid = quote.best_bid_price;<br>        price.timestamp = quote.timestamp;<br>        let (name, expiration, strike, kind) =<br>            decompose_option_name(&amp;quote.instrument_name);<br>        price.option_type = OptionType::from_str(<br>            kind.ok_or_else(|| anyhow::anyhow!(&quot;Missing option type&quot;))?<br>        );<br>        price.underlying = name<br>            .ok_or_else(|| anyhow::anyhow!(&quot;Error when parsing name&quot;))?.to_string();<br>        price.strike = strike<br>            .ok_or_else(|| anyhow::anyhow!(&quot;Missing strike&quot;))?<br>            .parse::&lt;f64&gt;()?;<br>        price.expiration = expiration_to_timestamp(<br>            expiration.ok_or_else(|| anyhow::anyhow!(&quot;Missing expiration&quot;))?<br>        )?;<br>        let bench = std::time::SystemTime::now()<br>            .duration_since(UNIX_EPOCH)?<br>            .as_secs();<br>        if price.timestamp &gt; bench {<br>            price.timestamp /= 1000;<br>        }<br>        Ok(price)<br>    }</pre><p>Here we return a Result&lt;Self&gt; to be able to ignore quote that haven’t be parsed correctly.</p><h3>Building the IV surface</h3><p>We now have all the components required to go from raw Deribit messages to a structure containing the implied volatilities and risk-neutral probabilities.</p><p>The output will be organized by expiration and strike:</p><p>Surface[Expiration][Strike] = Price</p><p>Since different expirations may have different available strikes, we also need to keep the strike values associated with each expiration. Finally, we sort both expirations and strikes in ascending order so that we can interpolate between them later.</p><pre>#[derive(Debug)]<br>pub struct IVSurface {<br>    pub iv: Vec&lt;Vec&lt;f64&gt;&gt;,<br>    pub market_proba: Vec&lt;Vec&lt;f64&gt;&gt;,<br>    pub keys: HashMap&lt;u64, Vec&lt;f64&gt;&gt;,<br>}</pre><p>Here, iv contains the implied volatility for each option, while market_proba contains the corresponding risk-neutral probabilities annualized. The keys map associates each expiration with its sorted list of strikes.</p><p>To construct the surface, we first collect all available expirations and sort them. For each expiration, we select the corresponding call options, sort them by strike, and calculate their implied volatility and probability using the latest underlying price, the following code is doing that.</p><pre>impl IVSurface {<br>    pub fn new(price: Vec&lt;&amp;OptionPrice&gt;, underlying_price: f64) -&gt; Self {<br>        // get all expiration<br>        let mut strike = Vec::new();<br>        let mut expiration = Vec::new();<br>        price.iter().for_each(|p| {if !strike.contains(&amp;p.strike) { strike.push(p.strike)   }<br>                                                  if !expiration.contains(&amp;p.expiration) { expiration.push(p.expiration) }   }<br>                                                    );<br>        strike.sort_by(|&amp;a, b| a.total_cmp(b));<br>        expiration.sort();<br>        let mut iv: Vec&lt;Vec&lt;f64&gt;&gt; = Vec::with_capacity(expiration.len());<br>        let mut market_proba: Vec&lt;Vec&lt;f64&gt;&gt; = Vec::with_capacity(expiration.len());<br>        let mut keys = HashMap::new(); <br>        for exp in expiration.iter() {<br>            let mut all_price: Vec&lt;&amp;&amp;OptionPrice&gt; = price.iter().filter(|&amp;p| p.expiration == *exp &amp;&amp; p.option_type == OptionType::Call).collect();<br>            all_price.sort_by(|a, b| a.strike.total_cmp(&amp;b.strike));<br>            <br>            let mut iv_by_expiration = Vec::with_capacity(all_price.len());<br>            let mut strike_by_expiration = Vec::with_capacity(all_price.len());<br>            let mut probas_by_expiration = Vec::with_capacity(all_price.len());<br>            <br>            for price in all_price.iter() {<br>                iv_by_expiration.push(price.get_iv(underlying_price));<br>                strike_by_expiration.push(price.strike);<br>                probas_by_expiration.push(price.risk_neutral_price(underlying_price));<br>            }<br>            <br>            iv.push(iv_by_expiration);<br>            market_proba.push(probas_by_expiration);<br>            keys.insert(*exp, strike_by_expiration);<br>            }<br>         Self { iv, market_proba, keys }<br>        }</pre><h3>Init the pricing engine</h3><p>The final step is to build the engine that retrieves option prices from Deribit, identifies their underlying assets, calculates implied volatilities and risk-neutral probabilities, constructs the IVSurface, and sends it to another task for further use, such as arbitrage analysis or model calibration.</p><p>We first need to decide how to organize the data. Since the client provides market data for several instruments, we need to know which instruments belong to each underlying.</p><p>The simplest solution is to store this information in a structure such as:</p><pre>HashMap&lt;String, Vec&lt;String&gt;&gt;</pre><p>where each key identifies an underlying and its value contains the associated instruments.</p><p>We also need to store the underlying price. One possibility would be to combine both pieces of information into a single map:</p><pre>HashMap&lt;String, (Vec&lt;String&gt;, f64)&gt;</pre><p>However, I chose to use two separate HashMaps because I find this structure easier to read. Since performance is not a critical constraint for this implementation, the additional storage required for the duplicated keys is not an issue.</p><p>We can now initialize the engine by retrieving the active instruments, filtering them by counter-currency, and fetching the corresponding underlying index price.</p><p>Code:</p><pre>const CURRENCY: &amp;str = &quot;USDC&quot;;<br>const COUNTER_CURRENCY: &amp;str = &quot;USD&quot;;<br>const RF: f64 = 0.04; // @todo get yied curve risk free rate<br><br>#[derive(Debug)]<br>pub struct DeribitEngine {    <br>    client: DeribitClient,<br>    instruments_deribit: HashMap&lt;String, Vec&lt;String&gt;&gt;,<br>    underlying_price: HashMap&lt;String, f64&gt;<br>}</pre><blockquote>Note: Here, we set RF as a constant value for quick testing; however, in production, we should use the actual US Treasury yield curve.</blockquote><p>Engine init:</p><pre>impl DeribitEngine {<br>    pub async fn new(underlyings: Vec&lt;String&gt;) -&gt; Self {<br>        let client = DeribitClient::new().unwrap();<br>        let mut instruments_deribit = HashMap::new();<br>        let mut underlying_price = HashMap::new();<br>        for underlying in underlyings.into_iter() {<br>            let u_instruments = client.get_instruments(&amp;underlying, Some(false)).await.unwrap().result;<br>            let mut u_instruments: Vec&lt;String&gt; = u_instruments.into_iter()<br>                                                              .filter(|l| l.counter_currency == COUNTER_CURRENCY)<br>                                                              .map(|l| l.instrument_name)<br>                                                              .collect();<br>            let underlying_name = format!(&quot;{underlying}_{CURRENCY}&quot;);<br>            let underlying_index_price = client.get_price(&amp;underlying_name).await.unwrap();<br>            u_instruments.push(underlying_name);<br>            instruments_deribit.entry(underlying.clone()).or_insert(u_instruments);<br>            <br>            underlying_price.entry(underlying).or_insert(underlying_index_price.result.index_price);<br>        }<br>        Self {instruments_deribit, client, underlying_price}<br>    }<br>}</pre><pre>Here, we retrieve all instruments that have not expired and filter them to <br>keep only those denominated in dollars. Finally, we initialize the underlying <br>asset&#39;s price and add its futures contract name to the channels so that we <br>also receive price updates for it.</pre><pre>pub async fn run(&amp;mut self, sender: Sender&lt;HashMap&lt;String, IVSurface&gt;&gt;, sending_time: Option&lt;u64&gt;) {<br>        let sending_time = sending_time.unwrap_or(10); // every 10 second<br>        let params = self.init_run_parameters();<br>        let (sx, mut tx) = mpsc::channel(100);<br>        let client = self.client.clone(); // Arc clone<br>        let mut price = HashMap::new();<br>        tokio::spawn(async move { if let Err(e) = client.connect_ws(params, None, sx).await {<br>                                                                 eprintln!(&quot;WS Error: {e:?}&quot;);<br>                                                            } <br>                                                    }<br>                                            );<br>        let mut time_waited = Instant::now();                                            <br>        while let Some(message) = tx.recv().await {<br>            let _ = self.handle_message(message, &amp;mut price);<br>            if Instant::now().duration_since(time_waited).as_secs() &gt; sending_time {<br>                println!(&quot;Sending IV surface !&quot;);<br>                time_waited = Instant::now();<br>                self.send_iv_surface(&amp;price, &amp;sender).await;<br>                println!(&quot;IV surface successfully send !&quot;)<br>            }<br>        } <br>        }</pre><p>The main loop runs continuously. It receives messages from the Deribit client, updates the stored market data, and sends the volatility surface to another task at regular intervals.</p><p>We initialize the subscription parameters using the instruments stored during engine initialization. We then spawn a background task to run the WebSocket client.</p><p>Each incoming message is passed to handle_message. This function checks whether the message is a valid subscription update and then distinguishes between underlying-price updates and option quotes.</p><p>For an underlying update, we only need the mid-price. For an option quote, we convert the raw message into an OptionPrice structure and replace the previously stored quote for that instrument.</p><p>This means that the engine only keeps the latest known quote for each instrument. Historical data storage is not handled here; it would need to be implemented by the task receiving the surface, or added as a separate component.</p><pre>fn handle_message(&amp;mut self, message: Message, price: &amp;mut HashMap&lt;String, OptionPrice&gt;) -&gt; Result&lt;(), Error&gt; {<br>        <br>        if let Ok(update) = serde_json::from_str::&lt;QuoteUpdate&gt;(message.to_text()?) {<br>            if update.method == &quot;subscription&quot; {<br>                if update.params.data.instrument_name.ends_with(CURRENCY) {<br>                    let ud = &amp;update.params.data.instrument_name.split(&quot;_&quot;).nth(0).unwrap();<br>                    let quote = &amp;update.params.data;<br>                    let mid = (quote.best_ask_price + quote.best_bid_price) / 2.0;<br>                    *self.underlying_price.get_mut(*ud).unwrap() = mid;<br>                }<br>             else {<br>                    let quote = update.params.data;<br>                    if let Ok(mut opt_price) = OptionPrice::from_quote(&amp;quote) {<br>                        self.convert_option_price_to_currency(&amp;mut opt_price);<br>                        price.insert(quote.instrument_name, opt_price);<br>                    }<br>                }<br>                }        <br>        }<br>        Ok(())<br>    }</pre><p>send_iv_surface:</p><pre>async fn send_iv_surface(&amp;self, price: &amp;HashMap&lt;String, OptionPrice&gt;, sender: &amp;Sender&lt;HashMap&lt;String, IVSurface&gt;&gt;) {<br>        let mut send_iv_surface = HashMap::new();<br>        for (underlying_name, underlying_derivatives) in self.instruments_deribit.iter() {<br>                    if let Some(underlying_price) = self.underlying_price.get(underlying_name) {<br>                        let mut option_price: Vec&lt;&amp;OptionPrice&gt; = Vec::with_capacity(underlying_derivatives.len());<br>                        <br>                        underlying_derivatives.iter().for_each(|u| {if let Some(p) = price.get(u) {<br>                                                                                option_price.push(p);<br>                                                                            }});        <br>                        let iv_surface = IVSurface::new(option_price, *underlying_price);<br>                        send_iv_surface.insert(underlying_name.clone(), iv_surface);<br>                        <br>                    }<br>                }<br>                <br>                sender.send(send_iv_surface).await.unwrap();<br>            }</pre><p>The send_iv_surface function is relatively simple. We iterate over the available underlyings, retrieve the corresponding option quotes, build an IVSurface for each underlying, and send the resulting map to the receiving task.</p><p>At this point, the engine can theoretically estimate the risk-neutral price of a binary contract such as:</p><blockquote><strong><em>BTC &gt; X in two days</em></strong></blockquote><p>provided that the relevant strike and maturity are covered by the available options, or can be interpolated within the surface.</p><p>Bellow is an exemple of what IV_Surface can be for BTC-USD</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXbpkw1HKMuh4Lak2owLag.png" /></figure><p>As you can see some IV are inf which mean we either have error in our parsing for their specific strike, or there’s no bid or no ask for them meaning mid is actually NaN, I prefer to keep them to know that there’s an option here, but if we want to remove them we can filter option in send_iv_surface with: bid.is_finite() &amp;&amp; ask.is_finite().</p><p>Now we almost can make a price many strike and expiration, however we want to do it for all expiration and all strike, meaning the last problem to solve is interpolation. If we want to estimate the probability of an event at strike 60000$, but we only have market data for 50000$ and 70000$ options, we need a way to estimate the value between these two maturities.</p><p>The simplest approach is linear interpolation. It is equivalent to drawing a straight line between two known points. This can be sufficient when we have enough observations and only need an estimate between nearby points.</p><h4>Linear Interpolation</h4><p>for ai in [0:1]</p><p>f(x) = ∑ai*x1 + (1-ai)*x2</p><p>Code:</p><pre>pub fn linear_interp(<br>    x: &amp;[f64],<br>    y: &amp;[f64],<br>    n_coeff: usize,<br>) -&gt; (Vec&lt;f64&gt;, Vec&lt;f64&gt;) {<br>    assert_eq!(x.len(), y.len());</pre><pre>    if x.len() &lt; 2 || n_coeff == 0 {<br>        return (x.to_vec(), y.to_vec());<br>    }</pre><pre>    let mut interp_x = Vec::new();<br>    let mut interp_y = Vec::new();</pre><pre>    for i in 0..x.len() - 1 {<br>        let x1 = x[i];<br>        let x2 = x[i + 1];<br>        let y1 = y[i];<br>        let y2 = y[i + 1];</pre><pre>        for j in 0..n_coeff {<br>            let alpha = j as f64 / n_coeff as f64;</pre><pre>            interp_x.push(x1 + alpha * (x2 - x1));<br>            interp_y.push(y1 + alpha * (y2 - y1));<br>        }<br>    }</pre><pre>    interp_x.push(*x.last().unwrap());<br>    interp_y.push(*y.last().unwrap());</pre><pre>    (interp_x, interp_y)<br>}</pre><p>We can now use it by making a grid for strike and interpolate all the value to get either iv or binary price across many strikes.</p><pre>pub fn linear_interpolation_strikes(&amp;mut self, n_coeff: usize) {<br>    let mut new_iv = Vec::with_capacity(self.iv.len());<br>    let mut new_proba = Vec::with_capacity(self.market_proba.len());<br>    let mut new_keys = HashMap::new();</pre><pre>    let mut expirations: Vec&lt;u64&gt; = self.keys.keys().copied().collect();<br>    expirations.sort_unstable();<br>    <br>    for (i, expiration) in expirations.iter().enumerate() {<br>        let strikes = self.keys.get(expiration).unwrap();<br>    <br>        let iv = &amp;self.iv[i];<br>        let market_proba = &amp;self.market_proba[i];<br>        let (interp_strikes, interp_iv) =<br>            linear_interp(strikes, iv, n_coeff);</pre><pre>        let (_, interp_proba) =<br>            linear_interp(strikes, market_proba, n_coeff);</pre><pre>        new_keys.insert(*expiration, interp_strikes);<br>        new_iv.push(interp_iv);<br>        new_proba.push(interp_proba);<br>    }</pre><pre>    self.iv = new_iv;<br>    self.market_proba = new_proba;<br>    self.keys = new_keys;<br>    }</pre><p>This interpolation have the benefit to be simple, however, this doesn’t guarantee that the resulting price are arbitrage-fee. In future work, I would like to explore arbitrage-aware methods for constructing volatility surfaces, including approaches such as those discussed by Carr and Madan or with VAE.</p><h3>Conclusion</h3><p>We now have a first working pipeline for retrieving market data from Deribit and transforming option quotes into a structured surface of implied volatilities and binary prices.</p><p>The client handles communication and market-data retrieval, while the pricing engine processes incoming quotes and periodically builds the surface. Separating these components makes the client reusable and keeps the pricing logic independent from the communication layer.</p><p>This implementation is a first step toward pricing more complex binary contracts. For contracts comparing two assets, such as BTC outperforming gold at a given date, we would need to model their joint dynamics and estimate the event probability through simulation.</p><p>In a future article, I will explore different modeling approaches, including neural networks, and investigate how they can be used to price these more complex contracts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c405934da79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Think Like a Solver in Poker]]></title>
            <link>https://medium.com/@ducrocqarsene/how-to-think-like-a-solver-in-poker-ecb51336fe99?source=rss-2f14e3d80313------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb51336fe99</guid>
            <category><![CDATA[poker]]></category>
            <category><![CDATA[probability-theory]]></category>
            <category><![CDATA[modern-poker]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[poker-online]]></category>
            <dc:creator><![CDATA[Arsène Ducrocq]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 09:50:40 GMT</pubDate>
            <atom:updated>2026-09-02T09:50:40.411Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the beginning of game solvers based on algorithms such as minimax, games like chess and poker have increasingly been dominated by programs, and humans have progressively become spectators of the improvement of game strategies through solvers.</p><h4>What Do We Optimize?</h4><p>In poker, a solver tries to maximize its EV (expected value) for each action. This means that, for each decision at time <em>T</em>, it estimates the EV of all available actions by building a tree of possible outcomes.</p><p>In games like poker, however, the number of possible outcomes is astronomical. Modern poker solvers therefore use techniques such as counterfactual regret minimization (CFR) and, in some cases, machine learning to approximate the solution without having to explicitly reconstruct every possible outcome. How these models work is outside the scope of this article, but I may write an article about this subject in the future.</p><h4>The Importance of the River</h4><p>If you have ever used a solver tool such as GTO Wizard, you may have noticed that the EVs of different postflop actions are often quite close to each other on the flop and turn.</p><p>One reason is that a large part of the EV generated postflop comes from decisions made later in the hand, especially on the river. This is why your strategy should be heavily river-oriented.</p><p>But why the river?</p><p>To answer this, you have to think of poker as a strategic game where, at the flop, you already have an idea of how your strategy will evolve depending on the turn and river cards. You should know which hands are going to bet, check, bluff, or value bet on different runouts.</p><p>The important thing to do on the flop and turn is therefore to make sure that your range remains well constructed in every branch of your strategy. Each branch should contain both strong and weak hands so that you cannot become predictable when the river comes.</p><p>For example, suppose you always check the flop and turn when you have nothing, and then decide to make a pot-sized bet on the river whenever you miss. Your river betting range will contain far too many weak hands. A good opponent can exploit this by simply calling more often or raising your bets.</p><p>The goal of your flop and turn strategy should therefore not only be to maximize the EV of the current decision. It should also be to <strong>build a range that allows you to make strong and balanced decisions on the river.</strong></p><h4>Optimizing the River Like a Solver</h4><p>To optimize your strategy like a solver, you can follow three main steps:</p><ol><li><strong>Know what you have in your range.</strong><br>This is the most important step. Without knowing the composition of your range, you cannot construct a balanced strategy.</li><li><strong>Estimate the equity of your hands against your opponent’s range.</strong><br>You don’t need to know your opponent’s range exactly. However, having a good estimate of the equity of your individual combos is extremely important. It allows you to group strong and weak hands together in the same strategy, for example when deciding which hands should go all-in.</li><li><strong>Optimize your strategy.</strong><br>Choose your sizing. For each sizing, determine which hands are value bets and which hands are bluffs, then calculate the appropriate ratio between value and bluff combos.</li></ol><p>In this section, we’re going to look at step 3 in more detail using a simple toy example.</p><pre>Opponent range: 99 (6 combos), 88 (6 combos) <br>Hero range: 22 (6 combos), QQ (6 combos) <br>Board: [A, J, 3, T, 6] (We don&#39;t care about suits in this example.) <br><br>Step 2: <br>QQ -&gt; 100% equity <br>22 -&gt; 0% equity <br><br>Step 3: <br>Ask yourself: What sizing do I want to use with my strongest hands? <br>Here, it is obvious that we want to go all-in with our hands that have 100% equity. <br><br>All-in strategy: The value-to-bluff ratio will depend on the effective SPR (stack-to-pot ratio). <br>SPR_effective = min(Hero_stack, Opponent_stack) / Pot <br>In this example, we are going to use SPR = 1 and leave the other sizings as an <br>exercise for the reader. <br><br>Choose the sizing: <br>With SPR = 1, the relevant formula is: Pot / (3 × Pot) = 1/3 <br>This is intuitive: if you bet the pot, your opponent has to call one pot-sized bet <br>to win a pot of 3 × pot. Therefore, they need to be correct 33% of the time to <br>make the call break even. This means that, in a balanced strategy, you should <br>have 1/3 bluffs and 2/3 value hands. <br>Recall our combos: <br>6 × 2/3 = 4 value combos <br>6 × 1/3 = 2 bluff combos <br>Therefore, the all-in strategy with an SPR of 1 consists of: 4 combos of QQ <br>2 combos of 22 We can also check the other possible combos. <br>The optimal strategy for our opponent when facing our check is also to go all-in. <br>If you calculate the EV for both players, you will obtain an equilibrium where <br>neither player can improve their EV by unilaterally changing their strategy.</pre><blockquote>This simple example illustrates the basic idea behind a solver: <strong>the goal is not simply to choose the action with the highest EV for one particular hand, but to construct a strategy in which your entire range is appropriately distributed across actions.</strong></blockquote><h4>Why Be Balanced?</h4><p>In the previous example, we saw how to construct a balanced strategy. But why do we need to be balanced in the first place?</p><p>This is the frontier between being <strong>balanced</strong> and being <strong>exploitable</strong>.</p><p>Recall our previous example. If we know that our opponent will call our all-in 50% of the time instead of the theoretically optimal 33%, then we should adjust our strategy and include more value hands in our all-in range.</p><p>The tricky part is that if our opponent notices that we are adjusting our strategy to exploit them, they can respond by changing their own strategy.</p><p>This creates a game of strategic interaction: if your opponent is unbalanced, you can exploit them. But once they realize that you are exploiting them, they can adjust their strategy and potentially exploit your adjustment.</p><p>To build a good intuition for this concept of equilibrium and exploitation, you can reproduce the exercise above with simplified poker spots or with other toy games such as rock-paper-scissors.</p><h4>Going to the River</h4><p>In this last section, we are going to discuss how to choose the optimal path for our strategy.</p><p>The actions you take on the flop and turn should facilitate the construction of your river strategy while making your opponent’s decisions as difficult as possible.</p><p>As we discussed earlier, your river range should contain different types of hands: very strong hands mixed with weak hands, medium-strength hands mixed with medium-strength bluffs, and so on.</p><p>This means that for every action you take on the flop and turn, you should think about what your future bluffs and value hands will be.</p><p>You should also consider whether an action gives you more information about your opponent’s range.</p><p>For example, suppose you are hesitating between checking and making a small bet. If the small bet significantly narrows your opponent’s range and makes your river decision easier, it may be preferable — even if the EV of the two actions is very close.</p><p>This is an important way of thinking like a solver.</p><p>A small EV difference on the flop may matter much less than the quality of the river decision that the action creates.</p><p>In other words, <strong>you should not only optimize the current decision. You should optimize the entire path your range will take through the hand.</strong></p><h4>Summary</h4><p>In this article, we saw how a solver constructs a balanced strategy and how we can use the same principles to improve our own decision-making.</p><p>The main idea is to stop thinking about poker as a sequence of isolated decisions. Instead, think of your strategy as a <strong>tree of interconnected decisions</strong>.</p><p>On the river, your range needs to contain an appropriate mixture of value hands and bluffs. This means that the decisions you make on the flop and turn should not only maximize their immediate EV; they should also help you construct a strong and difficult-to-exploit river range.</p><p>The three main steps are:</p><ol><li><strong>Know your range.</strong> Understand which hands can reach each decision point and how they are distributed.</li><li><strong>Estimate equity.</strong> You don’t need perfect knowledge of your opponent’s range, but you need a good enough estimate to distinguish between value hands, bluffs, and marginal hands.</li><li><strong>Construct your strategy.</strong> Choose your sizings and distribute your value hands and bluffs according to the underlying pot odds and strategic constraints.</li></ol><p>Finally, being balanced does not mean that you should blindly play GTO. If your opponent is making systematic mistakes, the optimal strategy is often to exploit them.</p><p>The real skill is therefore knowing <strong>when to be balanced and when to deviate from equilibrium to exploit your opponent.</strong></p><p>Thinking like a solver means looking beyond the EV of your next action and asking a deeper question:</p><p><strong>“How does this decision shape the rest of my range and the decisions I will have to make later?”</strong></p><p>That is the mindset I believe can help bridge the gap between simply using a solver and actually learning to think like one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb51336fe99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve option’s pricing speed using Rust and Polars]]></title>
            <link>https://medium.com/@ducrocqarsene/improve-options-pricing-speed-using-rust-and-polars-95ea68be351c?source=rss-2f14e3d80313------2</link>
            <guid isPermaLink="false">https://medium.com/p/95ea68be351c</guid>
            <category><![CDATA[polar]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Arsène Ducrocq]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 14:51:27 GMT</pubDate>
            <atom:updated>2026-08-21T14:51:27.861Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the inception of electronic markets, speed has become a key source of alpha. In options markets in particular, a quintessential zero-sum game, if your opponent is faster than you, you will likely lose money. This is why sophisticated firms use collocated servers, build custom hardware, and optimize every layer of their stack just to gain a 5-nanosecond edge over the competition. In high-frequency trading, execution speed is just as important as the alpha itself.</p><p>In this article, we look at a practical example using the <strong>Black-Scholes</strong> model to transform a typical native Python/Pandas workflow into a high-performance, production-ready pipeline using <strong>Rust</strong> and <strong>Polars</strong>.</p><h3>Step 1. Install maturin and init project</h3><pre>pip install maturin</pre><pre>maturin init price_engine</pre><p>Cargo.toml</p><pre>[package]<br>name = &quot;price_engine&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2024&quot;<br><br># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html<br>[lib]<br>name = &quot;price_engine&quot;<br>crate-type = [&quot;cdylib&quot;]<br><br>[dependencies]<br>itertools = &quot;0.15.0&quot;<br>polars = { version = &quot;*&quot; }<br>pyo3 = { version = &quot;*&quot;, features = [&quot;extension-module&quot;, &quot;abi3-py310&quot;] }<br>pyo3-polars = { version = &quot;*&quot;, features = [&quot;derive&quot;] }</pre><h3>Step 2: Write the Rust Engine</h3><p>Recall black-sholes formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*kiH1LSSzc1Tcq3Va" /></figure><p>To maintain clean architecture and easily add other models later, we define a generic trait:</p><pre>trait PricingModel {<br>    fn new(s: f64, k: f64, sigma: f64, tau: f64, rho: f64) -&gt; Self;<br>    fn get_price(&amp;self, option_type: &amp;str) -&gt; f64;<br>    fn vega(&amp;self, option_type: &amp;str) -&gt; f64;<br>    fn delta(&amp;self, option_type: &amp;str) -&gt; f64;<br>    fn gamma(&amp;self, option_type: &amp;str) -&gt; f64;<br>    fn theta(&amp;self, option_type: &amp;str) -&gt; f64;<br>}<br></pre><blockquote><strong><em>Note:</em></strong><em> A cleaner approach for the </em><em>new signature would be passing a dedicated parameters struct, which offers greater flexibility for different models.</em></blockquote><h4>Helper Function:</h4><pre>fn norm_pdf(x: f64) -&gt; f64 {<br>    (-0.5 * x * x).exp() / (2.0 * PI).sqrt()<br>}<br><br>fn norm_cdf(x: f64) -&gt; f64 {<br>    let k = 1.0 / (1.0 + 0.2316419 * x.abs());<br>    let poly = k * (0.319381530 + k * (-0.356563782 + k * (1.781477937 + k * (-1.821255978 + 1.330274429 * k))));<br>    let cdf = 1.0 - norm_pdf(x.abs()) * poly;<br>    <br>    if x &lt; 0.0 { 1.0 - cdf } else { cdf }<br>}</pre><p>The BlackSholes struct must be decorated with #[pyclass] if we want to instantiate it directly in Python. This is not strictly necessary for Polars plugin expressions, but it is useful for debugging and standalone execution:</p><pre>#[pyclass]<br>pub struct BlackSholes {<br>    pub s: f64,    <br>    pub k: f64,    <br>    pub sigma: f64, <br>    pub tau: f64,   <br>    pub rho: f64,   <br>}</pre><p>Implementing the Trait for BlackSholes framework:</p><pre><br>impl PricingModel for BlackSholes {<br>    fn new(s: f64, k: f64, sigma: f64, tau: f64, rho: f64) -&gt; Self {<br>        Self { s, k, sigma, tau, rho }<br>    }<br><br>    fn get_price(&amp;self, option_type: &amp;str) -&gt; f64 {<br>        let d1 = self.d1();<br>        let d2 = self.d2();<br>        if option_type.to_lowercase() == &quot;call&quot; {<br>            self.s * norm_cdf(d1) - self.k * (-self.rho * self.tau).exp() * norm_cdf(d2) <br>        } else {<br>            self.k * (-self.rho * self.tau).exp() * norm_cdf(-d2) - self.s * norm_cdf(-d1)<br>        }<br>    }<br><br>    fn vega(&amp;self, option_type: &amp;str) -&gt; f64 {<br>        self.s * self.tau.sqrt() * norm_pdf(self.d1())<br>    }<br><br>    fn delta(&amp;self, option_type: &amp;str) -&gt; f64 {<br>        if option_type.to_lowercase() == &quot;call&quot; {<br>            norm_cdf(self.d1())<br>        } else {<br>            norm_cdf(self.d1()) - 1.0 <br>        }<br>    }<br><br>    fn gamma(&amp;self, option_type: &amp;str) -&gt; f64 {<br>        norm_pdf(self.d1()) / (self.s * self.sigma * self.tau.sqrt())<br>    }<br><br>    fn theta(&amp;self, option_type: &amp;str) -&gt; f64 {<br>        let d1 = self.d1();<br>        let d2 = self.d2();<br>        let term1 = -(self.s * norm_pdf(d1) * self.sigma) / (2.0 * self.tau.sqrt());<br><br>        if option_type.to_lowercase() == &quot;call&quot; {<br>            let term2 = self.rho * self.k * (-self.rho * self.tau).exp() * norm_cdf(d2);<br>            term1 - term2<br>        } else {<br>            let term2 = self.rho * self.k * (-self.rho * self.tau).exp() * norm_cdf(-d2);<br>            term1 + term2<br>        }<br>    }<br>}</pre><p>Analytical Terms (d1, d2) and Python Methods</p><pre>#[pymethods]<br>impl BlackSholes {<br>    pub fn d1(&amp;self) -&gt; f64 {<br>        let numerator = (self.s / self.k).ln() + (self.rho + 0.5 * self.sigma.powi(2)) * self.tau;<br>        let denominator = self.sigma * self.tau.sqrt();<br>        numerator / denominator<br>    }<br><br>    pub fn d2(&amp;self) -&gt; f64 {<br>        self.d1() - self.sigma * self.tau.sqrt()<br>    }<br><br>    fn get_price_python(&amp;self, option_type: String) -&gt; f64 {<br>        let d1 = self.d1();<br>        let d2 = self.d2();<br>        if option_type.to_lowercase() == &quot;call&quot; {<br>            self.s * norm_cdf(d1) - self.k * (-self.rho * self.tau).exp() * norm_cdf(d2) <br>        } else {<br>            self.k * (-self.rho * self.tau).exp() * norm_cdf(-d2) - self.s * norm_cdf(-d1)<br>        }<br>    }<br> <br>}</pre><ul><li><em>Note:</em> Iadded get_price_python with an owned String parameter instead of &amp;str, making boundary calls across PyO3 simpler.</li></ul><h3>Step 3: Writing the Polars Plugin Expression</h3><p>Now for the interesting part: using the #[polars_expr] macro to write custom expressions and leverage the raw speed of Rust directly in Python via Polars.</p><p>Here is how we calculate the option’s delta:</p><pre>#[polars_expr(output_type=Float64)]<br>pub fn get_delta(s: &amp;[Series]) -&gt; PolarsResult&lt;Series&gt; {<br>    let vol = s[0].f64()?;<br>    let current_price = s[1].f64()?;<br>    let strike = s[2].f64()?;<br>    let tau = s[3].f64()?;<br>    let rho = s[4].f64()?;<br>    let opt_type = s[5].str()?;<br><br>    let output: Float64Chunked = izip!(<br>        vol.iter(),<br>        current_price.iter(),<br>        strike.iter(),<br>        tau.iter(),<br>        rho.iter(),<br>        opt_type.iter()<br>    )<br>    .map(|(vol, current_price, strike, tau, rho, opt_type)| {<br>        match (vol, current_price, strike, tau, rho, opt_type) {<br>            (Some(sigma), Some(price), Some(strike), Some(t), Some(r), Some(opt)) =&gt; {<br>                Some(BlackSholes::new(price, strike, sigma, t, r).delta(opt))<br>            }<br>            _ =&gt; None,<br>        }<br>    })<br>    .collect();<br><br>    Ok(output.into_series())<br>}</pre><p><strong>How it works:</strong></p><ul><li><strong>Function signature:</strong> The #[polars_expr] macro expects s: &amp;[Series] containing input series.</li><li><strong>Vectorized iteration:</strong> The izip! macro zips all iterator chunks together into a tuple stream, avoiding manual index lookups.</li><li><strong>Element-wise execution:</strong> The .map() closure processes each row safely, handling missing values (None) gracefully before collecting into a Float64Chunked series.</li></ul><h3>Step 4: Python Bindings &amp; Plugin Registration</h3><p>Create the Python package structure:</p><pre>mkdir -p price_engine/price_engine</pre><blockquote>price_engine/price_engine/__init__.py</blockquote><pre>from pathlib import Path<br>import polars as pl<br>from polars.plugins import register_plugin_function<br><br>LIB_PATH = Path(__file__).parent<br><br>def get_delta(<br>    volatility: pl.Expr | str,<br>    current_price: pl.Expr | str,<br>    strike: pl.Expr | str,<br>    tau: pl.Expr | str,<br>    rho: pl.Expr | str,<br>    opt_type: pl.Expr | str<br>) -&gt; pl.Expr:<br><br>    return register_plugin_function(<br>        args=[volatility, current_price, strike, tau, rho, opt_type],<br>        plugin_path=LIB_PATH,<br>        function_name=&quot;get_delta&quot;,<br>        is_elementwise=True, <br>    )</pre><p>register_plugin_function bridges our compiled Rust library and the Python Polars engine. The order in args must match the indices expected in Rust (s[0] = volatility, s[1] = current_price, etc.).</p><p>Build and install locally:</p><pre>maturin develop</pre><h3>Step 5: Running at Scale in Python</h3><p>We can now call our Rust plugin directly inside Polars query expressions:</p><pre>from price_engine import get_iv, get_delta<br>import polars as pl<br><br>RF = 3/100<br><br>def process_option_df(opt: pl.DataFrame):<br>    return (opt.with_columns(<br>        pl.col(&quot;Date&quot;).str.to_datetime(format=&quot;%Y-%m-%dT%H:%M:%S%.fZ&quot;).dt.cast_time_unit(&quot;us&quot;).alias(&quot;date_dt&quot;),<br>        pl.col(&quot;maturity&quot;).str.to_datetime(format=&quot;%Y-%m-%dT%H:%M:%S&quot;).dt.cast_time_unit(&quot;us&quot;).alias(&quot;maturity_dt&quot;),<br>    )<br>    .with_columns(<br>        tau=(pl.col(&quot;maturity_dt&quot;) - pl.col(&quot;date_dt&quot;)).dt.total_seconds() / (3600 * 24 * 365),<br>        rf=pl.lit(RF)<br>    )<br>    .with_columns(<br>        iv_bid = get_iv(&quot;Bid&quot;, &quot;UnderlyingPrice&quot;, &quot;strike&quot;, &quot;tau&quot;, &quot;rf&quot;, &quot;type&quot;),<br>        iv_ask = get_iv(&quot;Ask&quot;, &quot;UnderlyingPrice&quot;, &quot;strike&quot;, &quot;tau&quot;, &quot;rf&quot;, &quot;type&quot;),<br><br>    )<br>    .with_columns(<br>        delta_bid = get_delta(&quot;iv_bid&quot;, &quot;UnderlyingPrice&quot;, &quot;strike&quot;, &quot;tau&quot;, &quot;rf&quot;, &quot;type&quot;),<br>        delta_ask = get_delta(&quot;iv_ask&quot;, &quot;UnderlyingPrice&quot;, &quot;strike&quot;, &quot;tau&quot;, &quot;rf&quot;, &quot;type&quot;),<br>    )<br>    )</pre><p>With this pattern, you get the simplicity and expressiveness of Python for research, backed by the raw performance of multithreaded Rust for processing millions of options contracts in real time.</p><p>Enjoy reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95ea68be351c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>