Skip to main content

nautilus_model/python/data/
option_chain.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::collections::BTreeMap;
17
18use nautilus_core::{UnixNanos, python::to_pyvalue_err};
19use pyo3::prelude::*;
20
21use crate::{
22    data::{
23        QuoteTick,
24        greeks::OptionGreekValues,
25        option_chain::{OptionChainSlice, OptionGreeks, OptionStrikeData, StrikeRange},
26    },
27    enums::GreeksConvention,
28    identifiers::{InstrumentId, OptionSeriesId},
29    types::Price,
30};
31
32/// Python wrapper for `StrikeRange` (complex enum).
33#[pyclass(name = "StrikeRange", module = "nautilus_trader.model", from_py_object)]
34#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")]
35#[derive(Clone, Debug)]
36pub struct PyStrikeRange {
37    pub inner: StrikeRange,
38}
39
40#[pymethods]
41#[pyo3_stub_gen::derive::gen_stub_pymethods]
42impl PyStrikeRange {
43    /// Creates a `StrikeRange::Fixed` variant.
44    #[staticmethod]
45    #[pyo3(name = "fixed")]
46    fn py_fixed(strikes: Vec<Price>) -> Self {
47        Self {
48            inner: StrikeRange::Fixed(strikes),
49        }
50    }
51
52    /// Creates a `StrikeRange::AtmRelative` variant.
53    #[staticmethod]
54    #[pyo3(name = "atm_relative")]
55    fn py_atm_relative(strikes_above: usize, strikes_below: usize) -> Self {
56        Self {
57            inner: StrikeRange::AtmRelative {
58                strikes_above,
59                strikes_below,
60            },
61        }
62    }
63
64    /// Creates a `StrikeRange::AtmPercent` variant.
65    #[staticmethod]
66    #[pyo3(name = "atm_percent")]
67    fn py_atm_percent(pct: f64) -> PyResult<Self> {
68        let inner = StrikeRange::atm_percent(pct).map_err(to_pyvalue_err)?;
69        Ok(Self { inner })
70    }
71
72    /// Creates a `StrikeRange::Delta` variant.
73    #[staticmethod]
74    #[pyo3(name = "delta")]
75    fn py_delta(target: f64, tolerance: f64) -> PyResult<Self> {
76        let inner = StrikeRange::delta(target, tolerance).map_err(to_pyvalue_err)?;
77        Ok(Self { inner })
78    }
79
80    /// Returns the variant name (`Fixed`, `AtmRelative`, `AtmPercent`, or `Delta`).
81    #[getter]
82    #[pyo3(name = "kind")]
83    fn py_kind(&self) -> &'static str {
84        match self.inner {
85            StrikeRange::Fixed(_) => "Fixed",
86            StrikeRange::AtmRelative { .. } => "AtmRelative",
87            StrikeRange::AtmPercent { .. } => "AtmPercent",
88            StrikeRange::Delta { .. } => "Delta",
89        }
90    }
91
92    fn __repr__(&self) -> String {
93        format!("{:?}", self.inner)
94    }
95
96    fn __str__(&self) -> String {
97        format!("{:?}", self.inner)
98    }
99}
100
101#[pymethods]
102#[pyo3_stub_gen::derive::gen_stub_pymethods]
103impl OptionGreeks {
104    /// Exchange-provided option Greeks and implied volatility for a single instrument.
105    #[new]
106    #[pyo3(signature = (instrument_id, delta, gamma, vega, theta, rho=0.0, mark_iv=None, bid_iv=None, ask_iv=None, underlying_price=None, open_interest=None, ts_event=0, ts_init=0, convention=None))]
107    #[expect(clippy::too_many_arguments)]
108    fn py_new(
109        instrument_id: InstrumentId,
110        delta: f64,
111        gamma: f64,
112        vega: f64,
113        theta: f64,
114        rho: f64,
115        mark_iv: Option<f64>,
116        bid_iv: Option<f64>,
117        ask_iv: Option<f64>,
118        underlying_price: Option<f64>,
119        open_interest: Option<f64>,
120        ts_event: u64,
121        ts_init: u64,
122        convention: Option<GreeksConvention>,
123    ) -> Self {
124        Self {
125            instrument_id,
126            convention: convention.unwrap_or_default(),
127            greeks: OptionGreekValues {
128                delta,
129                gamma,
130                vega,
131                theta,
132                rho,
133            },
134            mark_iv,
135            bid_iv,
136            ask_iv,
137            underlying_price,
138            open_interest,
139            ts_event: UnixNanos::from(ts_event),
140            ts_init: UnixNanos::from(ts_init),
141        }
142    }
143
144    #[getter]
145    #[pyo3(name = "convention")]
146    fn py_convention(&self) -> GreeksConvention {
147        self.convention
148    }
149
150    #[getter]
151    #[pyo3(name = "instrument_id")]
152    fn py_instrument_id(&self) -> InstrumentId {
153        self.instrument_id
154    }
155
156    #[getter]
157    #[pyo3(name = "delta")]
158    fn py_delta(&self) -> f64 {
159        self.greeks.delta
160    }
161
162    #[getter]
163    #[pyo3(name = "gamma")]
164    fn py_gamma(&self) -> f64 {
165        self.greeks.gamma
166    }
167
168    #[getter]
169    #[pyo3(name = "vega")]
170    fn py_vega(&self) -> f64 {
171        self.greeks.vega
172    }
173
174    #[getter]
175    #[pyo3(name = "theta")]
176    fn py_theta(&self) -> f64 {
177        self.greeks.theta
178    }
179
180    #[getter]
181    #[pyo3(name = "rho")]
182    fn py_rho(&self) -> f64 {
183        self.greeks.rho
184    }
185
186    #[getter]
187    #[pyo3(name = "mark_iv")]
188    fn py_mark_iv(&self) -> Option<f64> {
189        self.mark_iv
190    }
191
192    #[getter]
193    #[pyo3(name = "bid_iv")]
194    fn py_bid_iv(&self) -> Option<f64> {
195        self.bid_iv
196    }
197
198    #[getter]
199    #[pyo3(name = "ask_iv")]
200    fn py_ask_iv(&self) -> Option<f64> {
201        self.ask_iv
202    }
203
204    #[getter]
205    #[pyo3(name = "underlying_price")]
206    fn py_underlying_price(&self) -> Option<f64> {
207        self.underlying_price
208    }
209
210    #[getter]
211    #[pyo3(name = "open_interest")]
212    fn py_open_interest(&self) -> Option<f64> {
213        self.open_interest
214    }
215
216    #[getter]
217    #[pyo3(name = "ts_event")]
218    fn py_ts_event(&self) -> u64 {
219        self.ts_event.as_u64()
220    }
221
222    #[getter]
223    #[pyo3(name = "ts_init")]
224    fn py_ts_init(&self) -> u64 {
225        self.ts_init.as_u64()
226    }
227
228    fn __repr__(&self) -> String {
229        format!("{self}")
230    }
231
232    fn __str__(&self) -> String {
233        format!("{self}")
234    }
235}
236
237#[pymethods]
238#[pyo3_stub_gen::derive::gen_stub_pymethods]
239impl OptionStrikeData {
240    /// Combined quote and Greeks data for a single strike in an option chain.
241    #[new]
242    #[pyo3(signature = (quote, greeks=None))]
243    fn py_new(quote: QuoteTick, greeks: Option<OptionGreeks>) -> Self {
244        Self { quote, greeks }
245    }
246
247    #[getter]
248    #[pyo3(name = "quote")]
249    fn py_quote(&self) -> QuoteTick {
250        self.quote
251    }
252
253    #[getter]
254    #[pyo3(name = "greeks")]
255    fn py_greeks(&self) -> Option<OptionGreeks> {
256        self.greeks
257    }
258
259    fn __repr__(&self) -> String {
260        format!(
261            "OptionStrikeData(quote={}, greeks={:?})",
262            self.quote, self.greeks
263        )
264    }
265}
266
267#[pymethods]
268#[pyo3_stub_gen::derive::gen_stub_pymethods]
269impl OptionChainSlice {
270    /// A point-in-time snapshot of an option chain for a single series.
271    #[new]
272    #[pyo3(signature = (series_id, atm_strike=None, ts_event=0, ts_init=0))]
273    fn py_new(
274        series_id: OptionSeriesId,
275        atm_strike: Option<Price>,
276        ts_event: u64,
277        ts_init: u64,
278    ) -> Self {
279        Self {
280            series_id,
281            atm_strike,
282            calls: BTreeMap::new(),
283            puts: BTreeMap::new(),
284            ts_event: UnixNanos::from(ts_event),
285            ts_init: UnixNanos::from(ts_init),
286        }
287    }
288
289    #[getter]
290    #[pyo3(name = "series_id")]
291    fn py_series_id(&self) -> OptionSeriesId {
292        self.series_id
293    }
294
295    #[getter]
296    #[pyo3(name = "atm_strike")]
297    fn py_atm_strike(&self) -> Option<Price> {
298        self.atm_strike
299    }
300
301    #[getter]
302    #[pyo3(name = "ts_event")]
303    fn py_ts_event(&self) -> u64 {
304        self.ts_event.as_u64()
305    }
306
307    #[getter]
308    #[pyo3(name = "ts_init")]
309    fn py_ts_init(&self) -> u64 {
310        self.ts_init.as_u64()
311    }
312
313    /// Returns the number of call entries.
314    #[pyo3(name = "call_count")]
315    fn py_call_count(&self) -> usize {
316        self.call_count()
317    }
318
319    /// Returns the number of put entries.
320    #[pyo3(name = "put_count")]
321    fn py_put_count(&self) -> usize {
322        self.put_count()
323    }
324
325    /// Returns the total number of unique strikes.
326    #[pyo3(name = "strike_count")]
327    fn py_strike_count(&self) -> usize {
328        self.strike_count()
329    }
330
331    /// Returns `true` if the chain has no data.
332    #[pyo3(name = "is_empty")]
333    fn py_is_empty(&self) -> bool {
334        self.is_empty()
335    }
336
337    /// Returns all strike prices present in the chain (union of calls and puts).
338    #[pyo3(name = "strikes")]
339    fn py_strikes(&self) -> Vec<Price> {
340        self.strikes()
341    }
342
343    /// Returns the call data for a given strike price.
344    #[pyo3(name = "get_call")]
345    fn py_get_call(&self, strike: Price) -> Option<OptionStrikeData> {
346        self.get_call(&strike).cloned()
347    }
348
349    /// Returns the put data for a given strike price.
350    #[pyo3(name = "get_put")]
351    fn py_get_put(&self, strike: Price) -> Option<OptionStrikeData> {
352        self.get_put(&strike).cloned()
353    }
354
355    /// Returns the call quote for a given strike price.
356    #[pyo3(name = "get_call_quote")]
357    fn py_get_call_quote(&self, strike: Price) -> Option<QuoteTick> {
358        self.get_call_quote(&strike).copied()
359    }
360
361    /// Returns the put quote for a given strike price.
362    #[pyo3(name = "get_put_quote")]
363    fn py_get_put_quote(&self, strike: Price) -> Option<QuoteTick> {
364        self.get_put_quote(&strike).copied()
365    }
366
367    /// Returns the call Greeks for a given strike price.
368    #[pyo3(name = "get_call_greeks")]
369    fn py_get_call_greeks(&self, strike: Price) -> Option<OptionGreeks> {
370        self.get_call_greeks(&strike).copied()
371    }
372
373    /// Returns the put Greeks for a given strike price.
374    #[pyo3(name = "get_put_greeks")]
375    fn py_get_put_greeks(&self, strike: Price) -> Option<OptionGreeks> {
376        self.get_put_greeks(&strike).copied()
377    }
378
379    fn __repr__(&self) -> String {
380        format!("{self}")
381    }
382
383    fn __str__(&self) -> String {
384        format!("{self}")
385    }
386}