diff --git a/README.md b/README.md index 21544bc..4fb1680 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ uv run python benchmarks/benchmark_table.py - **Feature matrix** — multi-indicator DataFrame for ML pipelines (`ferro_ta.features`) - **Charting API** — matplotlib and plotly charts with indicator subplots (`ferro_ta.viz`) - **Data adapters** — pluggable adapter interface with CSV and in-memory implementations (`ferro_ta.adapters`) -- **Options/IV helpers** — IV rank, IV percentile, IV z-score on any IV series (`ferro_ta.options`) +- **Derivatives analytics** — IV rank/percentile/z-score, options pricing/Greeks/IV, futures basis/curve/roll, strategy schemas, and multi-leg payoff helpers (`ferro_ta.analysis.*`) - **Agentic tools** — stable LangChain/agent tool wrappers (`ferro_ta.tools`), end-to-end workflow orchestrator (`ferro_ta.workflow`) - **MCP server** — Model Context Protocol server for Cursor/Claude integration; run with `python -m ferro_ta.mcp` - **Observability / Logging** — `ferro_ta.enable_debug()`, `ferro_ta.log_call()`, `ferro_ta.benchmark()` and `ferro_ta.traced()` decorator for instrumentation @@ -118,7 +118,7 @@ Optional extras: pip install "ferro-ta[pandas]" # transparent pandas.Series support pip install "ferro-ta[polars]" # transparent polars.Series support pip install "ferro-ta[gpu]" # GPU-accelerated SMA/EMA/RSI via PyTorch (CUDA/MPS) -pip install "ferro-ta[options]" # Options/IV helpers (IV rank, percentile, z-score) +pip install "ferro-ta[options]" # Derivatives analytics helpers pip install "ferro-ta[mcp]" # MCP server for Cursor/Claude agent integration pip install "ferro-ta[all]" # all optional extras (excluding gpu) ``` @@ -150,6 +150,28 @@ macd_line, signal, histogram = MACD(close, fastperiod=12, slowperiod=26, signalp upper, middle, lower = BBANDS(close, timeperiod=5, nbdevup=2.0, nbdevdn=2.0) ``` +## Δ Derivatives Analytics + +```python +from ferro_ta.analysis.options import greeks, implied_volatility, option_price +from ferro_ta.analysis.futures import basis, curve_summary + +price = option_price(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call", model="bsm") +iv = implied_volatility(price, 100.0, 100.0, 0.05, 1.0, option_type="call", model="bsm") +g = greeks(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call", model="bsm") + +front_basis = basis(100.0, 103.0) +curve = curve_summary(100.0, [0.1, 0.5, 1.0], [101.0, 102.0, 104.0]) +``` + +The derivatives layer is analytics-only. It includes: + +- options pricing under Black-Scholes-Merton and Black-76 +- delta, gamma, vega, theta, and rho +- implied volatility inversion and smile metrics +- futures basis, carry, curve, and continuous-roll helpers +- typed strategy schemas and multi-leg payoff/Greeks aggregation + **Migrating from TA-Lib?** Just swap the import — the API is identical: ```python @@ -673,7 +695,8 @@ python/ferro_ta/ │ # statistic, cycle, pattern, price_transform, math_ops, extended) ├── data/ # Streaming, batch, chunked, resampling, aggregation, adapters ├── analysis/ # Portfolio, backtest, regime, cross_asset, attribution, -│ # signals, features, crypto, options +│ # signals, features, crypto, options, futures, +│ # options_strategy, derivatives_payoff ├── tools/ # Visualisation, alerting, DSL, pipeline, workflow, │ # api_info, GPU support └── mcp/ # Model Context Protocol server diff --git a/benchmarks/test_derivatives_speed.py b/benchmarks/test_derivatives_speed.py new file mode 100644 index 0000000..8388dda --- /dev/null +++ b/benchmarks/test_derivatives_speed.py @@ -0,0 +1,108 @@ +""" +Derivatives benchmark hooks. + +These are intentionally optional and skip when `py_vollib` is unavailable. +Run with: + + uv run pytest benchmarks/test_derivatives_speed.py --benchmark-only -v +""" + +from __future__ import annotations + +import importlib.util + +import numpy as np +import pytest + +from ferro_ta.analysis.options import implied_volatility, option_price + + +def _sample_chain(n: int = 1000) -> tuple[np.ndarray, ...]: + spot = np.linspace(90.0, 110.0, n) + strike = np.full(n, 100.0) + rate = np.full(n, 0.02) + time_to_expiry = np.full(n, 0.5) + volatility = np.full(n, 0.2) + return spot, strike, rate, time_to_expiry, volatility + + +def test_ferro_ta_option_price_speed(benchmark): + spot, strike, rate, time_to_expiry, volatility = _sample_chain() + + benchmark.pedantic( + lambda: option_price( + spot, + strike, + rate, + time_to_expiry, + volatility, + option_type="call", + model="bsm", + ), + iterations=5, + rounds=20, + warmup_rounds=2, + ) + + +def test_ferro_ta_implied_vol_speed(benchmark): + spot, strike, rate, time_to_expiry, volatility = _sample_chain() + prices = option_price( + spot, + strike, + rate, + time_to_expiry, + volatility, + option_type="call", + model="bsm", + ) + + benchmark.pedantic( + lambda: implied_volatility( + prices, + spot, + strike, + rate, + time_to_expiry, + option_type="call", + model="bsm", + ), + iterations=5, + rounds=20, + warmup_rounds=2, + ) + + +@pytest.mark.skipif( + importlib.util.find_spec("py_vollib") is None, + reason="py_vollib is optional", +) +def test_py_vollib_scalar_loop_baseline(benchmark): + from py_vollib.black_scholes_merton import black_scholes_merton as py_vollib_bsm + from py_vollib.black_scholes_merton.implied_volatility import ( + implied_volatility as py_vollib_iv, + ) + + spot, strike, rate, time_to_expiry, volatility = _sample_chain(250) + prices = [ + py_vollib_bsm("c", float(s), float(k), float(t), float(r), float(vol), 0.0) + for s, k, r, t, vol in zip(spot, strike, rate, time_to_expiry, volatility) + ] + + benchmark.pedantic( + lambda: [ + py_vollib_iv( + float(price), + "c", + float(s), + float(k), + float(t), + float(r), + 0.0, + ) + for price, s, k, r, t in zip(prices, spot, strike, rate, time_to_expiry) + ], + iterations=3, + rounds=10, + warmup_rounds=1, + ) diff --git a/crates/ferro_ta_core/benches/indicators.rs b/crates/ferro_ta_core/benches/indicators.rs index 0fd9ec1..9c74666 100644 --- a/crates/ferro_ta_core/benches/indicators.rs +++ b/crates/ferro_ta_core/benches/indicators.rs @@ -4,8 +4,9 @@ //! Or: cd crates/ferro_ta_core && cargo bench //! //! Input sizes: 1k, 10k, 100k, and 1M bars for key indicators. -use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; -use ferro_ta_core::{momentum, overlap, volatility}; +use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; +use ferro_ta_core::{futures, momentum, options, overlap, volatility}; +use std::hint::black_box; fn synthetic_close(n: usize) -> Vec { let mut v = Vec::with_capacity(n); @@ -83,12 +84,129 @@ fn bench_bbands(c: &mut Criterion) { group.finish(); } +fn bench_bsm_price(c: &mut Criterion) { + let mut group = c.benchmark_group("BSM_PRICE"); + for size in [1_000_usize, 10_000, 100_000] { + let close = synthetic_close(size); + let strikes: Vec = close.iter().map(|_| 100.0).collect(); + let vols: Vec = close.iter().map(|_| 0.2).collect(); + group.bench_with_input(BenchmarkId::from_parameter(size), &close, |b, close| { + b.iter(|| { + close + .iter() + .zip(strikes.iter()) + .zip(vols.iter()) + .map(|((&spot, &strike), &vol)| { + options::pricing::black_scholes_price( + black_box(spot), + black_box(strike), + black_box(0.02), + black_box(0.0), + black_box(0.5), + black_box(vol), + options::OptionKind::Call, + ) + }) + .collect::>() + }) + }); + } + group.finish(); +} + +fn bench_implied_volatility(c: &mut Criterion) { + let mut group = c.benchmark_group("IMPLIED_VOL"); + for size in [1_000_usize, 10_000] { + let prices: Vec = (0..size) + .map(|i| { + let spot = 90.0 + (i % 20) as f64; + options::pricing::black_scholes_price( + spot, + 100.0, + 0.02, + 0.0, + 0.5, + 0.2, + options::OptionKind::Call, + ) + }) + .collect(); + group.bench_with_input(BenchmarkId::from_parameter(size), &prices, |b, prices| { + b.iter(|| { + prices + .iter() + .enumerate() + .map(|(i, &price)| { + options::iv::implied_volatility( + options::OptionContract { + model: options::PricingModel::BlackScholes, + underlying: black_box(90.0 + (i % 20) as f64), + strike: black_box(100.0), + rate: black_box(0.02), + carry: black_box(0.0), + time_to_expiry: black_box(0.5), + kind: options::OptionKind::Call, + }, + black_box(price), + options::IvSolverConfig { + initial_guess: black_box(0.25), + tolerance: black_box(1e-8), + max_iterations: black_box(100), + }, + ) + }) + .collect::>() + }) + }); + } + group.finish(); +} + +fn bench_smile_metrics(c: &mut Criterion) { + let mut group = c.benchmark_group("SMILE_METRICS"); + let strikes: Vec = (0..41).map(|i| 80.0 + i as f64).collect(); + let vols: Vec = strikes + .iter() + .map(|&k| 0.18 + ((k - 100.0).abs() / 100.0) * 0.15) + .collect(); + group.bench_function("single_chain", |b| { + b.iter(|| { + options::surface::smile_metrics( + black_box(&strikes), + black_box(&vols), + black_box(100.0), + black_box(0.02), + black_box(0.0), + black_box(0.5), + options::PricingModel::BlackScholes, + ) + }) + }); + group.finish(); +} + +fn bench_curve_summary(c: &mut Criterion) { + let mut group = c.benchmark_group("FUTURES_CURVE"); + let tenors = vec![0.1, 0.25, 0.5, 0.75, 1.0]; + let prices = vec![101.0, 101.8, 102.7, 103.4, 104.1]; + group.bench_function("curve_summary", |b| { + b.iter(|| { + futures::curve::curve_summary(black_box(100.0), black_box(&tenors), black_box(&prices)) + }) + }); + group.finish(); +} + criterion_group!( benches, bench_sma, bench_ema, bench_rsi, bench_atr, - bench_bbands + bench_bbands, + bench_bsm_price, + bench_implied_volatility, + bench_smile_metrics, + bench_curve_summary ); criterion_main!(benches); diff --git a/crates/ferro_ta_core/src/futures/basis.rs b/crates/ferro_ta_core/src/futures/basis.rs new file mode 100644 index 0000000..f7e4ade --- /dev/null +++ b/crates/ferro_ta_core/src/futures/basis.rs @@ -0,0 +1,55 @@ +//! Basis and carry analytics. + +/// Futures basis: futures - spot. +pub fn basis(spot: f64, future: f64) -> f64 { + if !spot.is_finite() || !future.is_finite() { + f64::NAN + } else { + future - spot + } +} + +/// Annualized simple basis return. +pub fn annualized_basis(spot: f64, future: f64, time_to_expiry: f64) -> f64 { + if !spot.is_finite() + || !future.is_finite() + || !time_to_expiry.is_finite() + || spot <= 0.0 + || time_to_expiry <= 0.0 + { + return f64::NAN; + } + (future / spot - 1.0) / time_to_expiry +} + +/// Implied continuously compounded carry rate. +pub fn implied_carry_rate(spot: f64, future: f64, time_to_expiry: f64) -> f64 { + if !spot.is_finite() + || !future.is_finite() + || !time_to_expiry.is_finite() + || spot <= 0.0 + || future <= 0.0 + || time_to_expiry <= 0.0 + { + return f64::NAN; + } + (future / spot).ln() / time_to_expiry +} + +/// Carry spread relative to the risk-free rate. +pub fn carry_spread(spot: f64, future: f64, rate: f64, time_to_expiry: f64) -> f64 { + implied_carry_rate(spot, future, time_to_expiry) - rate +} + +#[cfg(test)] +mod tests { + use super::{annualized_basis, basis, carry_spread, implied_carry_rate}; + + #[test] + fn basis_helpers_work() { + assert_eq!(basis(100.0, 103.0), 3.0); + assert!(annualized_basis(100.0, 103.0, 0.25) > 0.0); + assert!(implied_carry_rate(100.0, 103.0, 0.25) > 0.0); + assert!(carry_spread(100.0, 103.0, 0.02, 0.25).is_finite()); + } +} diff --git a/crates/ferro_ta_core/src/futures/curve.rs b/crates/ferro_ta_core/src/futures/curve.rs new file mode 100644 index 0000000..773d7e4 --- /dev/null +++ b/crates/ferro_ta_core/src/futures/curve.rs @@ -0,0 +1,83 @@ +//! Futures curve and term-structure analytics. + +use super::basis; + +/// Curve summary metrics. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CurveSummary { + pub front_basis: f64, + pub average_basis: f64, + pub slope: f64, + pub is_contango: bool, +} + +fn regression_slope(xs: &[f64], ys: &[f64]) -> f64 { + if xs.len() != ys.len() || xs.len() < 2 { + return f64::NAN; + } + let n = xs.len() as f64; + let mean_x = xs.iter().sum::() / n; + let mean_y = ys.iter().sum::() / n; + let mut cov = 0.0; + let mut var = 0.0; + for (&x, &y) in xs.iter().zip(ys.iter()) { + cov += (x - mean_x) * (y - mean_y); + var += (x - mean_x) * (x - mean_x); + } + if var == 0.0 { + f64::NAN + } else { + cov / var + } +} + +/// Calendar spreads between adjacent contracts. +pub fn calendar_spreads(futures_prices: &[f64]) -> Vec { + futures_prices.windows(2).map(|w| w[1] - w[0]).collect() +} + +/// Curve slope across tenor buckets. +pub fn curve_slope(tenors: &[f64], futures_prices: &[f64]) -> f64 { + regression_slope(tenors, futures_prices) +} + +/// Summary statistics for a forward curve. +pub fn curve_summary(spot: f64, tenors: &[f64], futures_prices: &[f64]) -> CurveSummary { + if futures_prices.is_empty() || tenors.len() != futures_prices.len() { + return CurveSummary { + front_basis: f64::NAN, + average_basis: f64::NAN, + slope: f64::NAN, + is_contango: false, + }; + } + let bases: Vec = futures_prices + .iter() + .map(|&price| basis::basis(spot, price)) + .collect(); + let average_basis = bases.iter().sum::() / bases.len() as f64; + let is_contango = futures_prices.windows(2).all(|w| w[1] >= w[0]); + CurveSummary { + front_basis: basis::basis(spot, futures_prices[0]), + average_basis, + slope: curve_slope(tenors, futures_prices), + is_contango, + } +} + +#[cfg(test)] +mod tests { + use super::{calendar_spreads, curve_slope, curve_summary}; + + #[test] + fn calendar_spreads_are_correct() { + assert_eq!(calendar_spreads(&[100.0, 101.0, 103.0]), vec![1.0, 2.0]); + } + + #[test] + fn curve_summary_detects_contango() { + let summary = curve_summary(100.0, &[0.1, 0.5, 1.0], &[101.0, 102.0, 104.0]); + assert!(summary.is_contango); + assert!(curve_slope(&[0.1, 0.5, 1.0], &[101.0, 102.0, 104.0]) > 0.0); + } +} diff --git a/crates/ferro_ta_core/src/futures/mod.rs b/crates/ferro_ta_core/src/futures/mod.rs new file mode 100644 index 0000000..60fc1f6 --- /dev/null +++ b/crates/ferro_ta_core/src/futures/mod.rs @@ -0,0 +1,6 @@ +//! Futures analytics core. + +pub mod basis; +pub mod curve; +pub mod roll; +pub mod synthetic; diff --git a/crates/ferro_ta_core/src/futures/roll.rs b/crates/ferro_ta_core/src/futures/roll.rs new file mode 100644 index 0000000..6e08207 --- /dev/null +++ b/crates/ferro_ta_core/src/futures/roll.rs @@ -0,0 +1,109 @@ +//! Continuous futures roll helpers. + +/// Weighted stitching using next-contract weights in [0, 1]. +pub fn weighted_continuous(front: &[f64], next: &[f64], next_weights: &[f64]) -> Vec { + if front.len() != next.len() || front.len() != next_weights.len() { + return Vec::new(); + } + front + .iter() + .zip(next.iter()) + .zip(next_weights.iter()) + .map(|((&f, &n), &w)| f * (1.0 - w) + n * w) + .collect() +} + +fn roll_index(weights: &[f64]) -> Option { + if weights.is_empty() { + return None; + } + weights + .iter() + .enumerate() + .find(|(_, w)| **w >= 0.5) + .map(|(idx, _)| idx) + .or_else(|| weights.iter().position(|w| *w > 0.0)) + .or(Some(weights.len() - 1)) +} + +/// Back-adjusted continuous series using the roll date implied by the weights. +pub fn back_adjusted_continuous(front: &[f64], next: &[f64], next_weights: &[f64]) -> Vec { + if front.len() != next.len() || front.len() != next_weights.len() || front.is_empty() { + return Vec::new(); + } + let idx = roll_index(next_weights).unwrap_or(front.len() - 1); + let gap = next[idx] - front[idx]; + front + .iter() + .enumerate() + .map(|(i, &value)| if i < idx { value + gap } else { next[i] }) + .collect() +} + +/// Ratio-adjusted continuous series using the roll date implied by the weights. +pub fn ratio_adjusted_continuous(front: &[f64], next: &[f64], next_weights: &[f64]) -> Vec { + if front.len() != next.len() || front.len() != next_weights.len() || front.is_empty() { + return Vec::new(); + } + let idx = roll_index(next_weights).unwrap_or(front.len() - 1); + let ratio = if front[idx] == 0.0 { + 1.0 + } else { + next[idx] / front[idx] + }; + front + .iter() + .enumerate() + .map(|(i, &value)| if i < idx { value * ratio } else { next[i] }) + .collect() +} + +/// Annualized roll yield from front and next prices. +pub fn roll_yield(front_price: f64, next_price: f64, time_to_expiry: f64) -> f64 { + if !front_price.is_finite() + || !next_price.is_finite() + || !time_to_expiry.is_finite() + || front_price <= 0.0 + || time_to_expiry <= 0.0 + { + return f64::NAN; + } + (next_price / front_price - 1.0) / time_to_expiry +} + +#[cfg(test)] +mod tests { + use super::{ + back_adjusted_continuous, ratio_adjusted_continuous, roll_yield, weighted_continuous, + }; + + #[test] + fn weighted_roll_blends_contracts() { + let out = weighted_continuous(&[100.0, 101.0], &[102.0, 103.0], &[0.0, 1.0]); + assert_eq!(out, vec![100.0, 103.0]); + } + + #[test] + fn adjusted_rolls_return_full_series() { + let weights = [0.0, 0.25, 0.75, 1.0]; + assert_eq!( + back_adjusted_continuous( + &[100.0, 101.0, 102.0, 103.0], + &[101.0, 102.0, 103.0, 104.0], + &weights + ) + .len(), + 4 + ); + assert_eq!( + ratio_adjusted_continuous( + &[100.0, 101.0, 102.0, 103.0], + &[101.0, 102.0, 103.0, 104.0], + &weights + ) + .len(), + 4 + ); + assert!(roll_yield(100.0, 102.0, 30.0 / 365.0).is_finite()); + } +} diff --git a/crates/ferro_ta_core/src/futures/synthetic.rs b/crates/ferro_ta_core/src/futures/synthetic.rs new file mode 100644 index 0000000..02a9acd --- /dev/null +++ b/crates/ferro_ta_core/src/futures/synthetic.rs @@ -0,0 +1,78 @@ +//! Synthetic futures helpers built from put-call parity. + +/// Synthetic forward price from call/put parity. +pub fn synthetic_forward( + call_price: f64, + put_price: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, +) -> f64 { + if !call_price.is_finite() + || !put_price.is_finite() + || !strike.is_finite() + || !rate.is_finite() + || !time_to_expiry.is_finite() + || strike <= 0.0 + || time_to_expiry < 0.0 + { + return f64::NAN; + } + (call_price - put_price) * (rate * time_to_expiry).exp() + strike +} + +/// Synthetic spot price implied by call/put parity with continuous carry. +pub fn synthetic_spot( + call_price: f64, + put_price: f64, + strike: f64, + rate: f64, + carry: f64, + time_to_expiry: f64, +) -> f64 { + if !call_price.is_finite() + || !put_price.is_finite() + || !strike.is_finite() + || !rate.is_finite() + || !carry.is_finite() + || !time_to_expiry.is_finite() + || strike <= 0.0 + || time_to_expiry < 0.0 + { + return f64::NAN; + } + (call_price - put_price + strike * (-rate * time_to_expiry).exp()) + * (carry * time_to_expiry).exp() +} + +/// Put-call parity residual. Zero means the inputs are parity-consistent. +pub fn parity_gap( + call_price: f64, + put_price: f64, + spot: f64, + strike: f64, + rate: f64, + carry: f64, + time_to_expiry: f64, +) -> f64 { + call_price + - put_price + - (spot * (-carry * time_to_expiry).exp() - strike * (-rate * time_to_expiry).exp()) +} + +#[cfg(test)] +mod tests { + use super::{parity_gap, synthetic_forward}; + + #[test] + fn synthetic_forward_is_consistent() { + let forward = synthetic_forward(8.0, 5.0, 100.0, 0.02, 0.5); + assert!(forward > 100.0); + } + + #[test] + fn parity_gap_zero_when_consistent() { + let gap = parity_gap(10.45, 5.57, 100.0, 100.0, 0.05, 0.0, 1.0); + assert!(gap.abs() < 0.05); + } +} diff --git a/crates/ferro_ta_core/src/lib.rs b/crates/ferro_ta_core/src/lib.rs index a04a659..9ee0cd5 100644 --- a/crates/ferro_ta_core/src/lib.rs +++ b/crates/ferro_ta_core/src/lib.rs @@ -26,8 +26,10 @@ assert!((sma[2] - 2.0).abs() < 1e-10); ``` */ +pub mod futures; pub mod math; pub mod momentum; +pub mod options; pub mod overlap; pub mod statistic; pub mod volatility; diff --git a/crates/ferro_ta_core/src/options/chain.rs b/crates/ferro_ta_core/src/options/chain.rs new file mode 100644 index 0000000..a716ae4 --- /dev/null +++ b/crates/ferro_ta_core/src/options/chain.rs @@ -0,0 +1,162 @@ +//! Option chain analytics helpers. + +use super::greeks::model_greeks; +use super::{ChainGreeksContext, OptionContract, OptionEvaluation, OptionKind}; + +/// Return the index of the strike closest to the reference price. +pub fn atm_index(strikes: &[f64], reference_price: f64) -> Option { + if strikes.is_empty() || !reference_price.is_finite() { + return None; + } + strikes + .iter() + .enumerate() + .filter(|(_, strike)| strike.is_finite()) + .min_by(|(_, a), (_, b)| { + (*a - reference_price) + .abs() + .partial_cmp(&(*b - reference_price).abs()) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .map(|(idx, _)| idx) +} + +/// Label strikes as ITM (1), ATM (0), or OTM (-1). +pub fn label_moneyness(strikes: &[f64], reference_price: f64, kind: OptionKind) -> Vec { + let mut labels = Vec::with_capacity(strikes.len()); + let atm_idx = atm_index(strikes, reference_price); + for (idx, &strike) in strikes.iter().enumerate() { + if Some(idx) == atm_idx { + labels.push(0); + continue; + } + let label = match kind { + OptionKind::Call => { + if strike < reference_price { + 1 + } else { + -1 + } + } + OptionKind::Put => { + if strike > reference_price { + 1 + } else { + -1 + } + } + }; + labels.push(label); + } + labels +} + +/// Select a strike relative to the ATM strike by offset steps. +pub fn select_strike_by_offset( + strikes: &[f64], + reference_price: f64, + offset: isize, +) -> Option { + let idx = atm_index(strikes, reference_price)? as isize + offset; + if idx < 0 || idx >= strikes.len() as isize { + None + } else { + Some(strikes[idx as usize]) + } +} + +/// Select the strike whose delta is closest to the requested target. +pub fn select_strike_by_delta( + strikes: &[f64], + vols: &[f64], + context: ChainGreeksContext, + target_delta: f64, +) -> Option { + if strikes.len() != vols.len() || strikes.is_empty() { + return None; + } + strikes + .iter() + .zip(vols.iter()) + .filter(|(strike, vol)| strike.is_finite() && vol.is_finite()) + .min_by(|(strike_a, vol_a), (strike_b, vol_b)| { + let delta_a = model_greeks(OptionEvaluation { + contract: OptionContract { + model: context.model, + underlying: context.reference_price, + strike: **strike_a, + rate: context.rate, + carry: context.carry, + time_to_expiry: context.time_to_expiry, + kind: context.kind, + }, + volatility: **vol_a, + }) + .delta; + let delta_b = model_greeks(OptionEvaluation { + contract: OptionContract { + model: context.model, + underlying: context.reference_price, + strike: **strike_b, + rate: context.rate, + carry: context.carry, + time_to_expiry: context.time_to_expiry, + kind: context.kind, + }, + volatility: **vol_b, + }) + .delta; + (delta_a - target_delta) + .abs() + .partial_cmp(&(delta_b - target_delta).abs()) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .map(|(strike, _)| *strike) +} + +#[cfg(test)] +mod tests { + use super::{atm_index, label_moneyness, select_strike_by_delta, select_strike_by_offset}; + use crate::options::{ChainGreeksContext, OptionKind, PricingModel}; + + #[test] + fn atm_index_finds_nearest() { + let strikes = [90.0, 100.0, 110.0]; + assert_eq!(atm_index(&strikes, 103.0), Some(1)); + } + + #[test] + fn moneyness_labels_calls() { + let strikes = [90.0, 100.0, 110.0]; + assert_eq!( + label_moneyness(&strikes, 100.0, OptionKind::Call), + vec![1, 0, -1] + ); + } + + #[test] + fn offset_selects_expected_strike() { + let strikes = [90.0, 100.0, 110.0]; + assert_eq!(select_strike_by_offset(&strikes, 101.0, 1), Some(110.0)); + } + + #[test] + fn delta_selection_returns_a_strike() { + let strikes = [80.0, 90.0, 100.0, 110.0, 120.0]; + let vols = [0.28, 0.24, 0.20, 0.22, 0.26]; + let strike = select_strike_by_delta( + &strikes, + &vols, + ChainGreeksContext { + model: PricingModel::BlackScholes, + reference_price: 100.0, + rate: 0.01, + carry: 0.0, + time_to_expiry: 0.5, + kind: OptionKind::Call, + }, + 0.25, + ); + assert!(strike.is_some()); + } +} diff --git a/crates/ferro_ta_core/src/options/greeks.rs b/crates/ferro_ta_core/src/options/greeks.rs new file mode 100644 index 0000000..fbc24cf --- /dev/null +++ b/crates/ferro_ta_core/src/options/greeks.rs @@ -0,0 +1,230 @@ +//! Option Greeks. + +use super::normal::{cdf, pdf}; +use super::pricing::{black_76_price, black_scholes_price}; +use super::{Greeks, OptionEvaluation, OptionKind, PricingModel}; + +fn bs_inputs_valid( + underlying: f64, + strike: f64, + rate: f64, + carry: f64, + time_to_expiry: f64, + volatility: f64, +) -> bool { + underlying.is_finite() + && strike.is_finite() + && rate.is_finite() + && carry.is_finite() + && time_to_expiry.is_finite() + && volatility.is_finite() + && underlying > 0.0 + && strike > 0.0 + && time_to_expiry > 0.0 + && volatility > 0.0 +} + +fn numerical_theta(time_to_expiry: f64, price_fn: F) -> f64 +where + F: Fn(f64) -> f64, +{ + if time_to_expiry <= 0.0 { + return 0.0; + } + let h = time_to_expiry.clamp(1e-6, 1.0 / 365.0); + let t_minus = (time_to_expiry - h).max(1e-8); + let t_plus = time_to_expiry + h; + let price_minus = price_fn(t_minus); + let price_plus = price_fn(t_plus); + (price_minus - price_plus) / (t_plus - t_minus) +} + +/// Black-Scholes-Merton Greeks. +pub fn black_scholes_greeks( + spot: f64, + strike: f64, + rate: f64, + dividend_yield: f64, + time_to_expiry: f64, + volatility: f64, + kind: OptionKind, +) -> Greeks { + if !bs_inputs_valid( + spot, + strike, + rate, + dividend_yield, + time_to_expiry, + volatility, + ) { + return Greeks { + delta: f64::NAN, + gamma: f64::NAN, + vega: f64::NAN, + theta: f64::NAN, + rho: f64::NAN, + }; + } + + let sqrt_t = time_to_expiry.sqrt(); + let sigma_sqrt_t = volatility * sqrt_t; + let discount = (-rate * time_to_expiry).exp(); + let carry_discount = (-dividend_yield * time_to_expiry).exp(); + let d1 = ((spot / strike).ln() + + (rate - dividend_yield + 0.5 * volatility * volatility) * time_to_expiry) + / sigma_sqrt_t; + let d2 = d1 - sigma_sqrt_t; + let pdf_d1 = pdf(d1); + + let delta = match kind { + OptionKind::Call => carry_discount * cdf(d1), + OptionKind::Put => carry_discount * (cdf(d1) - 1.0), + }; + let gamma = carry_discount * pdf_d1 / (spot * sigma_sqrt_t); + let vega = spot * carry_discount * pdf_d1 * sqrt_t; + let theta = match kind { + OptionKind::Call => { + -(spot * carry_discount * pdf_d1 * volatility) / (2.0 * sqrt_t) + - rate * strike * discount * cdf(d2) + + dividend_yield * spot * carry_discount * cdf(d1) + } + OptionKind::Put => { + -(spot * carry_discount * pdf_d1 * volatility) / (2.0 * sqrt_t) + + rate * strike * discount * cdf(-d2) + - dividend_yield * spot * carry_discount * cdf(-d1) + } + }; + let rho = match kind { + OptionKind::Call => strike * time_to_expiry * discount * cdf(d2), + OptionKind::Put => -strike * time_to_expiry * discount * cdf(-d2), + }; + + Greeks { + delta, + gamma, + vega, + theta, + rho, + } +} + +/// Black-76 Greeks with respect to the forward. +pub fn black_76_greeks( + forward: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + volatility: f64, + kind: OptionKind, +) -> Greeks { + if !bs_inputs_valid(forward, strike, rate, 0.0, time_to_expiry, volatility) { + return Greeks { + delta: f64::NAN, + gamma: f64::NAN, + vega: f64::NAN, + theta: f64::NAN, + rho: f64::NAN, + }; + } + + let sqrt_t = time_to_expiry.sqrt(); + let sigma_sqrt_t = volatility * sqrt_t; + let discount = (-rate * time_to_expiry).exp(); + let d1 = + ((forward / strike).ln() + 0.5 * volatility * volatility * time_to_expiry) / sigma_sqrt_t; + let pdf_d1 = pdf(d1); + + let delta = match kind { + OptionKind::Call => discount * cdf(d1), + OptionKind::Put => -discount * cdf(-d1), + }; + let gamma = discount * pdf_d1 / (forward * sigma_sqrt_t); + let vega = discount * forward * pdf_d1 * sqrt_t; + let theta = numerical_theta(time_to_expiry, |t| { + black_76_price(forward, strike, rate, t, volatility, kind) + }); + let rho = + -time_to_expiry * black_76_price(forward, strike, rate, time_to_expiry, volatility, kind); + + Greeks { + delta, + gamma, + vega, + theta, + rho, + } +} + +/// Model-dispatched Greeks. +pub fn model_greeks(input: OptionEvaluation) -> Greeks { + let contract = input.contract; + match contract.model { + PricingModel::BlackScholes => black_scholes_greeks( + contract.underlying, + contract.strike, + contract.rate, + contract.carry, + contract.time_to_expiry, + input.volatility, + contract.kind, + ), + PricingModel::Black76 => black_76_greeks( + contract.underlying, + contract.strike, + contract.rate, + contract.time_to_expiry, + input.volatility, + contract.kind, + ), + } +} + +/// Price derivative with respect to calendar time using the selected model. +pub fn model_theta(input: OptionEvaluation) -> f64 { + let contract = input.contract; + numerical_theta(contract.time_to_expiry, |t| match contract.model { + PricingModel::BlackScholes => black_scholes_price( + contract.underlying, + contract.strike, + contract.rate, + contract.carry, + t, + input.volatility, + contract.kind, + ), + PricingModel::Black76 => black_76_price( + contract.underlying, + contract.strike, + contract.rate, + t, + input.volatility, + contract.kind, + ), + }) +} + +#[cfg(test)] +mod tests { + use super::{black_76_greeks, black_scholes_greeks}; + use crate::options::OptionKind; + + #[test] + fn bsm_greeks_are_finite() { + let g = black_scholes_greeks(100.0, 100.0, 0.05, 0.0, 1.0, 0.2, OptionKind::Call); + assert!(g.delta.is_finite()); + assert!(g.gamma.is_finite()); + assert!(g.vega.is_finite()); + assert!(g.theta.is_finite()); + assert!(g.rho.is_finite()); + } + + #[test] + fn black_76_greeks_are_finite() { + let g = black_76_greeks(100.0, 100.0, 0.03, 1.0, 0.2, OptionKind::Put); + assert!(g.delta.is_finite()); + assert!(g.gamma.is_finite()); + assert!(g.vega.is_finite()); + assert!(g.theta.is_finite()); + assert!(g.rho.is_finite()); + } +} diff --git a/crates/ferro_ta_core/src/options/iv.rs b/crates/ferro_ta_core/src/options/iv.rs new file mode 100644 index 0000000..2302886 --- /dev/null +++ b/crates/ferro_ta_core/src/options/iv.rs @@ -0,0 +1,241 @@ +//! Implied volatility inversion and IV-series helpers. + +use super::greeks::model_greeks; +use super::pricing::{model_price, price_lower_bound, price_upper_bound}; +use super::{IvSolverConfig, OptionContract, OptionEvaluation}; + +/// Solve implied volatility with guarded Newton iterations and bisection fallback. +pub fn implied_volatility( + contract: OptionContract, + target_price: f64, + config: IvSolverConfig, +) -> f64 { + if !target_price.is_finite() + || !contract.underlying.is_finite() + || !contract.strike.is_finite() + || !contract.rate.is_finite() + || !contract.carry.is_finite() + || !contract.time_to_expiry.is_finite() + || target_price < 0.0 + || contract.underlying <= 0.0 + || contract.strike <= 0.0 + || contract.time_to_expiry < 0.0 + { + return f64::NAN; + } + if contract.time_to_expiry == 0.0 { + return 0.0; + } + + let lower = price_lower_bound(contract); + let upper = price_upper_bound(contract); + if target_price < lower - config.tolerance || target_price > upper + config.tolerance { + return f64::NAN; + } + if (target_price - lower).abs() <= config.tolerance { + return 0.0; + } + + let mut low_vol = 1e-9; + let mut high_vol = config.initial_guess.max(0.25).max(low_vol * 10.0); + let mut high_price = model_price(OptionEvaluation { + contract, + volatility: high_vol, + }); + while high_price < target_price && high_vol < 10.0 { + high_vol *= 2.0; + high_price = model_price(OptionEvaluation { + contract, + volatility: high_vol, + }); + } + if high_price < target_price { + return f64::NAN; + } + + let mut vol = config.initial_guess.clamp(low_vol, high_vol).max(1e-4); + for _ in 0..config.max_iterations.max(1) { + let price = model_price(OptionEvaluation { + contract, + volatility: vol, + }); + let diff = price - target_price; + if diff.abs() <= config.tolerance { + return vol; + } + + if diff > 0.0 { + high_vol = high_vol.min(vol); + } else { + low_vol = low_vol.max(vol); + } + + let vega = model_greeks(OptionEvaluation { + contract, + volatility: vol, + }) + .vega; + + let next = if vega.is_finite() && vega.abs() > 1e-10 { + let candidate = vol - diff / vega; + if candidate > low_vol && candidate < high_vol { + candidate + } else { + 0.5 * (low_vol + high_vol) + } + } else { + 0.5 * (low_vol + high_vol) + }; + vol = next; + } + + let final_price = model_price(OptionEvaluation { + contract, + volatility: vol, + }); + if (final_price - target_price).abs() <= config.tolerance * 10.0 { + vol + } else { + f64::NAN + } +} + +fn validate_window(window: usize) -> bool { + window >= 1 +} + +/// Rolling IV rank. +pub fn iv_rank(iv_series: &[f64], window: usize) -> Vec { + let n = iv_series.len(); + let mut out = vec![f64::NAN; n]; + if !validate_window(window) || n < window { + return out; + } + + for end in (window - 1)..n { + let start = end + 1 - window; + let mut min_v = f64::INFINITY; + let mut max_v = f64::NEG_INFINITY; + for &v in &iv_series[start..=end] { + if v.is_finite() { + min_v = min_v.min(v); + max_v = max_v.max(v); + } + } + let current = iv_series[end]; + if !current.is_finite() || !min_v.is_finite() || !max_v.is_finite() { + out[end] = f64::NAN; + continue; + } + let spread = max_v - min_v; + out[end] = if spread == 0.0 { + 0.0 + } else { + (current - min_v) / spread + }; + } + out +} + +/// Rolling IV percentile. +pub fn iv_percentile(iv_series: &[f64], window: usize) -> Vec { + let n = iv_series.len(); + let mut out = vec![f64::NAN; n]; + if !validate_window(window) || n < window { + return out; + } + + for end in (window - 1)..n { + let start = end + 1 - window; + let current = iv_series[end]; + let count = iv_series[start..=end] + .iter() + .filter(|&&v| v <= current) + .count(); + out[end] = count as f64 / window as f64; + } + out +} + +/// Rolling IV z-score. +pub fn iv_zscore(iv_series: &[f64], window: usize) -> Vec { + let n = iv_series.len(); + let mut out = vec![f64::NAN; n]; + if !validate_window(window) || n < window { + return out; + } + + for end in (window - 1)..n { + let start = end + 1 - window; + let mut count = 0usize; + let mut sum = 0.0; + for &v in &iv_series[start..=end] { + if v.is_finite() { + count += 1; + sum += v; + } + } + if count == 0 { + out[end] = f64::NAN; + continue; + } + let mean = sum / count as f64; + let mut var = 0.0; + for &v in &iv_series[start..=end] { + if v.is_finite() { + let d = v - mean; + var += d * d; + } + } + let std = (var / count as f64).sqrt(); + let current = iv_series[end]; + out[end] = if !current.is_finite() || std == 0.0 { + f64::NAN + } else { + (current - mean) / std + }; + } + out +} + +#[cfg(test)] +mod tests { + use super::{implied_volatility, iv_percentile, iv_rank, iv_zscore}; + use crate::options::pricing::black_scholes_price; + use crate::options::{IvSolverConfig, OptionContract, OptionKind, PricingModel}; + + #[test] + fn solver_recovers_input_vol() { + let price = black_scholes_price(100.0, 100.0, 0.05, 0.0, 1.0, 0.2, OptionKind::Call); + let iv = implied_volatility( + OptionContract { + model: PricingModel::BlackScholes, + underlying: 100.0, + strike: 100.0, + rate: 0.05, + carry: 0.0, + time_to_expiry: 1.0, + kind: OptionKind::Call, + }, + price, + IvSolverConfig { + initial_guess: 0.3, + tolerance: 1e-8, + max_iterations: 100, + }, + ); + assert!((iv - 0.2).abs() < 1e-6); + } + + #[test] + fn iv_helpers_match_expected_values() { + let iv = [10.0, 20.0, 30.0, 15.0, 22.0]; + let rank = iv_rank(&iv, 3); + let pct = iv_percentile(&iv, 3); + let z = iv_zscore(&iv, 3); + assert!(rank[0].is_nan() && rank[1].is_nan()); + assert!((rank[2] - 1.0).abs() < 1e-12); + assert!((pct[3] - (1.0 / 3.0)).abs() < 1e-12); + assert!((z[2] - 1.224_744_871).abs() < 1e-6); + } +} diff --git a/crates/ferro_ta_core/src/options/mod.rs b/crates/ferro_ta_core/src/options/mod.rs new file mode 100644 index 0000000..7046a01 --- /dev/null +++ b/crates/ferro_ta_core/src/options/mod.rs @@ -0,0 +1,88 @@ +//! Options analytics core. +//! +//! This module contains pricing, Greeks, implied volatility inversion, +//! IV-series helpers, and smile/chain utilities. The public API is scalar-first +//! and is used by the PyO3 bridge to build vectorized batch functions. + +pub mod chain; +pub mod greeks; +pub mod iv; +pub mod normal; +pub mod pricing; +pub mod surface; + +/// Option side. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum OptionKind { + /// Call option. + Call, + /// Put option. + Put, +} + +impl OptionKind { + /// Returns +1 for calls and -1 for puts. + pub fn sign(self) -> f64 { + match self { + Self::Call => 1.0, + Self::Put => -1.0, + } + } +} + +/// Supported pricing models. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PricingModel { + /// Black-Scholes-Merton with continuous carry/dividend yield. + BlackScholes, + /// Black-76 using the forward price as the underlying input. + Black76, +} + +/// Primary first-order Greeks returned by the pricing engine. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Greeks { + pub delta: f64, + pub gamma: f64, + pub vega: f64, + pub theta: f64, + pub rho: f64, +} + +/// Shared contract fields for model-based option analytics. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OptionContract { + pub model: PricingModel, + pub underlying: f64, + pub strike: f64, + pub rate: f64, + pub carry: f64, + pub time_to_expiry: f64, + pub kind: OptionKind, +} + +/// Contract plus volatility for pricing and Greeks. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OptionEvaluation { + pub contract: OptionContract, + pub volatility: f64, +} + +/// Solver configuration for implied volatility inversion. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct IvSolverConfig { + pub initial_guess: f64, + pub tolerance: f64, + pub max_iterations: usize, +} + +/// Shared context for strike selection and smile analytics. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChainGreeksContext { + pub model: PricingModel, + pub reference_price: f64, + pub rate: f64, + pub carry: f64, + pub time_to_expiry: f64, + pub kind: OptionKind, +} diff --git a/crates/ferro_ta_core/src/options/normal.rs b/crates/ferro_ta_core/src/options/normal.rs new file mode 100644 index 0000000..bb66380 --- /dev/null +++ b/crates/ferro_ta_core/src/options/normal.rs @@ -0,0 +1,44 @@ +//! Normal distribution helpers. + +const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7; + +/// Standard normal probability density function. +pub fn pdf(x: f64) -> f64 { + INV_SQRT_2PI * (-0.5 * x * x).exp() +} + +/// Standard normal cumulative distribution function. +/// +/// Uses a common Abramowitz-Stegun style approximation that is fast and +/// sufficiently accurate for option pricing work. +pub fn cdf(x: f64) -> f64 { + let ax = x.abs(); + let t = 1.0 / (1.0 + 0.231_641_9 * ax); + let poly = (((((1.330_274_429 * t - 1.821_255_978) * t) + 1.781_477_937) * t - 0.356_563_782) + * t + + 0.319_381_530) + * t; + let approx = 1.0 - pdf(ax) * poly; + if x >= 0.0 { + approx + } else { + 1.0 - approx + } +} + +#[cfg(test)] +mod tests { + use super::{cdf, pdf}; + + #[test] + fn cdf_is_reasonable() { + assert!((cdf(0.0) - 0.5).abs() < 1e-7); + assert!((cdf(1.0) - 0.841_344_746).abs() < 5e-5); + assert!((cdf(-1.0) - 0.158_655_254).abs() < 5e-5); + } + + #[test] + fn pdf_is_reasonable() { + assert!((pdf(0.0) - 0.398_942_280_4).abs() < 1e-10); + } +} diff --git a/crates/ferro_ta_core/src/options/pricing.rs b/crates/ferro_ta_core/src/options/pricing.rs new file mode 100644 index 0000000..d853baf --- /dev/null +++ b/crates/ferro_ta_core/src/options/pricing.rs @@ -0,0 +1,187 @@ +//! Option pricing models. + +use super::normal::cdf; +use super::{OptionContract, OptionEvaluation, OptionKind, PricingModel}; + +fn invalid_inputs(underlying: f64, strike: f64, time_to_expiry: f64, volatility: f64) -> bool { + !underlying.is_finite() + || !strike.is_finite() + || !time_to_expiry.is_finite() + || !volatility.is_finite() + || underlying <= 0.0 + || strike <= 0.0 + || time_to_expiry < 0.0 + || volatility < 0.0 +} + +/// Black-Scholes-Merton price with continuous carry/dividend yield. +pub fn black_scholes_price( + spot: f64, + strike: f64, + rate: f64, + dividend_yield: f64, + time_to_expiry: f64, + volatility: f64, + kind: OptionKind, +) -> f64 { + if invalid_inputs(spot, strike, time_to_expiry, volatility) || !rate.is_finite() { + return f64::NAN; + } + if time_to_expiry == 0.0 { + return match kind { + OptionKind::Call => (spot - strike).max(0.0), + OptionKind::Put => (strike - spot).max(0.0), + }; + } + + let discount = (-rate * time_to_expiry).exp(); + let carry_discount = (-dividend_yield * time_to_expiry).exp(); + if volatility == 0.0 { + return match kind { + OptionKind::Call => (spot * carry_discount - strike * discount).max(0.0), + OptionKind::Put => (strike * discount - spot * carry_discount).max(0.0), + }; + } + + let sqrt_t = time_to_expiry.sqrt(); + let sigma_sqrt_t = volatility * sqrt_t; + let d1 = ((spot / strike).ln() + + (rate - dividend_yield + 0.5 * volatility * volatility) * time_to_expiry) + / sigma_sqrt_t; + let d2 = d1 - sigma_sqrt_t; + + match kind { + OptionKind::Call => spot * carry_discount * cdf(d1) - strike * discount * cdf(d2), + OptionKind::Put => strike * discount * cdf(-d2) - spot * carry_discount * cdf(-d1), + } +} + +/// Black-76 price using the forward price as the underlying input. +pub fn black_76_price( + forward: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + volatility: f64, + kind: OptionKind, +) -> f64 { + if invalid_inputs(forward, strike, time_to_expiry, volatility) || !rate.is_finite() { + return f64::NAN; + } + let discount = (-rate * time_to_expiry).exp(); + if time_to_expiry == 0.0 { + return discount + * match kind { + OptionKind::Call => (forward - strike).max(0.0), + OptionKind::Put => (strike - forward).max(0.0), + }; + } + if volatility == 0.0 { + return discount + * match kind { + OptionKind::Call => (forward - strike).max(0.0), + OptionKind::Put => (strike - forward).max(0.0), + }; + } + + let sqrt_t = time_to_expiry.sqrt(); + let sigma_sqrt_t = volatility * sqrt_t; + let d1 = + ((forward / strike).ln() + 0.5 * volatility * volatility * time_to_expiry) / sigma_sqrt_t; + let d2 = d1 - sigma_sqrt_t; + + let signed = kind.sign(); + discount * signed * (forward * cdf(signed * d1) - strike * cdf(signed * d2)) +} + +/// Model-dispatched option price. +pub fn model_price(input: OptionEvaluation) -> f64 { + let contract = input.contract; + match contract.model { + PricingModel::BlackScholes => black_scholes_price( + contract.underlying, + contract.strike, + contract.rate, + contract.carry, + contract.time_to_expiry, + input.volatility, + contract.kind, + ), + PricingModel::Black76 => black_76_price( + contract.underlying, + contract.strike, + contract.rate, + contract.time_to_expiry, + input.volatility, + contract.kind, + ), + } +} + +/// Lower no-arbitrage bound for the option price. +pub fn price_lower_bound(contract: OptionContract) -> f64 { + match contract.model { + PricingModel::BlackScholes => { + let discount = (-contract.rate * contract.time_to_expiry).exp(); + let carry_discount = (-contract.carry * contract.time_to_expiry).exp(); + match contract.kind { + OptionKind::Call => { + (contract.underlying * carry_discount - contract.strike * discount).max(0.0) + } + OptionKind::Put => { + (contract.strike * discount - contract.underlying * carry_discount).max(0.0) + } + } + } + PricingModel::Black76 => { + let discount = (-contract.rate * contract.time_to_expiry).exp(); + discount + * match contract.kind { + OptionKind::Call => (contract.underlying - contract.strike).max(0.0), + OptionKind::Put => (contract.strike - contract.underlying).max(0.0), + } + } + } +} + +/// Upper no-arbitrage bound for the option price. +pub fn price_upper_bound(contract: OptionContract) -> f64 { + match contract.model { + PricingModel::BlackScholes => match contract.kind { + OptionKind::Call => { + contract.underlying * (-contract.carry * contract.time_to_expiry).exp() + } + OptionKind::Put => contract.strike * (-contract.rate * contract.time_to_expiry).exp(), + }, + PricingModel::Black76 => { + let discount = (-contract.rate * contract.time_to_expiry).exp(); + discount + * match contract.kind { + OptionKind::Call => contract.underlying, + OptionKind::Put => contract.strike, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{black_76_price, black_scholes_price}; + use crate::options::OptionKind; + + #[test] + fn black_scholes_prices_are_reasonable() { + let call = black_scholes_price(100.0, 100.0, 0.05, 0.0, 1.0, 0.2, OptionKind::Call); + let put = black_scholes_price(100.0, 100.0, 0.05, 0.0, 1.0, 0.2, OptionKind::Put); + assert!((call - 10.4506).abs() < 1e-3); + assert!((put - 5.5735).abs() < 1e-3); + } + + #[test] + fn black_76_prices_are_reasonable() { + let call = black_76_price(100.0, 100.0, 0.03, 1.0, 0.2, OptionKind::Call); + let put = black_76_price(100.0, 100.0, 0.03, 1.0, 0.2, OptionKind::Put); + assert!((call - 7.730_148).abs() < 1e-3); + assert!((put - 7.730_148).abs() < 1e-3); + } +} diff --git a/crates/ferro_ta_core/src/options/surface.rs b/crates/ferro_ta_core/src/options/surface.rs new file mode 100644 index 0000000..b3899af --- /dev/null +++ b/crates/ferro_ta_core/src/options/surface.rs @@ -0,0 +1,240 @@ +//! Smile and surface analytics helpers. + +use super::chain::atm_index; +use super::greeks::model_greeks; +use super::{ChainGreeksContext, OptionContract, OptionEvaluation, OptionKind, PricingModel}; + +/// Smile summary metrics. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SmileMetrics { + pub atm_iv: f64, + pub risk_reversal_25d: f64, + pub butterfly_25d: f64, + pub skew_slope: f64, + pub convexity: f64, +} + +/// Linear interpolation helper. +pub fn linear_interpolate(xs: &[f64], ys: &[f64], target: f64) -> f64 { + if xs.len() != ys.len() || xs.is_empty() { + return f64::NAN; + } + if target <= xs[0] { + return ys[0]; + } + for i in 1..xs.len() { + if target <= xs[i] { + let x0 = xs[i - 1]; + let x1 = xs[i]; + let y0 = ys[i - 1]; + let y1 = ys[i]; + let w = if x1 == x0 { + 0.0 + } else { + (target - x0) / (x1 - x0) + }; + return y0 + w * (y1 - y0); + } + } + ys[ys.len() - 1] +} + +/// ATM implied volatility by nearest strike. +pub fn atm_iv(strikes: &[f64], vols: &[f64], reference_price: f64) -> f64 { + if strikes.len() != vols.len() || strikes.is_empty() || !reference_price.is_finite() { + return f64::NAN; + } + atm_index(strikes, reference_price) + .and_then(|idx| vols.get(idx).copied()) + .unwrap_or(f64::NAN) +} + +fn regression_slope(xs: &[f64], ys: &[f64]) -> f64 { + if xs.len() != ys.len() || xs.len() < 2 { + return f64::NAN; + } + let n = xs.len() as f64; + let mean_x = xs.iter().sum::() / n; + let mean_y = ys.iter().sum::() / n; + let mut cov = 0.0; + let mut var = 0.0; + for (&x, &y) in xs.iter().zip(ys.iter()) { + cov += (x - mean_x) * (y - mean_y); + var += (x - mean_x) * (x - mean_x); + } + if var == 0.0 { + f64::NAN + } else { + cov / var + } +} + +fn closest_delta_iv( + strikes: &[f64], + vols: &[f64], + context: ChainGreeksContext, + target_delta: f64, +) -> f64 { + let mut best_iv = f64::NAN; + let mut best_distance = f64::INFINITY; + for (&strike, &vol) in strikes.iter().zip(vols.iter()) { + if !strike.is_finite() || !vol.is_finite() { + continue; + } + let delta = model_greeks(OptionEvaluation { + contract: OptionContract { + model: context.model, + underlying: context.reference_price, + strike, + rate: context.rate, + carry: context.carry, + time_to_expiry: context.time_to_expiry, + kind: context.kind, + }, + volatility: vol, + }) + .delta; + if !delta.is_finite() { + continue; + } + let distance = (delta - target_delta).abs(); + if distance < best_distance { + best_distance = distance; + best_iv = vol; + } + } + best_iv +} + +/// Smile metrics from a single expiry slice. +pub fn smile_metrics( + strikes: &[f64], + vols: &[f64], + reference_price: f64, + rate: f64, + carry: f64, + time_to_expiry: f64, + model: PricingModel, +) -> SmileMetrics { + if strikes.len() != vols.len() || strikes.len() < 3 || reference_price <= 0.0 { + return SmileMetrics { + atm_iv: f64::NAN, + risk_reversal_25d: f64::NAN, + butterfly_25d: f64::NAN, + skew_slope: f64::NAN, + convexity: f64::NAN, + }; + } + + let atm_idx = match atm_index(strikes, reference_price) { + Some(idx) => idx, + None => { + return SmileMetrics { + atm_iv: f64::NAN, + risk_reversal_25d: f64::NAN, + butterfly_25d: f64::NAN, + skew_slope: f64::NAN, + convexity: f64::NAN, + } + } + }; + let atm_iv = vols[atm_idx]; + + let call_25 = closest_delta_iv( + strikes, + vols, + ChainGreeksContext { + model, + reference_price, + rate, + carry, + time_to_expiry, + kind: OptionKind::Call, + }, + 0.25, + ); + let put_25 = closest_delta_iv( + strikes, + vols, + ChainGreeksContext { + model, + reference_price, + rate, + carry, + time_to_expiry, + kind: OptionKind::Put, + }, + -0.25, + ); + let risk_reversal_25d = call_25 - put_25; + let butterfly_25d = 0.5 * (call_25 + put_25) - atm_iv; + + let log_moneyness: Vec = strikes + .iter() + .map(|&k| (k / reference_price).ln()) + .collect(); + let skew_slope = regression_slope(&log_moneyness, vols); + let convexity = if atm_idx > 0 && atm_idx + 1 < strikes.len() { + let x0 = log_moneyness[atm_idx - 1]; + let x1 = log_moneyness[atm_idx]; + let x2 = log_moneyness[atm_idx + 1]; + let y0 = vols[atm_idx - 1]; + let y1 = vols[atm_idx]; + let y2 = vols[atm_idx + 1]; + let left = if x1 == x0 { 0.0 } else { (y1 - y0) / (x1 - x0) }; + let right = if x2 == x1 { 0.0 } else { (y2 - y1) / (x2 - x1) }; + right - left + } else { + f64::NAN + }; + + SmileMetrics { + atm_iv, + risk_reversal_25d, + butterfly_25d, + skew_slope, + convexity, + } +} + +/// Term-structure slope from (tenor, atm_iv) points. +pub fn term_structure_slope(tenors: &[f64], atm_ivs: &[f64]) -> f64 { + regression_slope(tenors, atm_ivs) +} + +#[cfg(test)] +mod tests { + use super::{atm_iv, smile_metrics, term_structure_slope}; + use crate::options::PricingModel; + + #[test] + fn atm_selection_works() { + let strikes = [90.0, 100.0, 110.0]; + let vols = [0.24, 0.20, 0.22]; + assert!((atm_iv(&strikes, &vols, 102.0) - 0.20).abs() < 1e-12); + } + + #[test] + fn smile_metrics_are_finite() { + let strikes = [80.0, 90.0, 100.0, 110.0, 120.0]; + let vols = [0.30, 0.25, 0.20, 0.22, 0.27]; + let metrics = smile_metrics( + &strikes, + &vols, + 100.0, + 0.02, + 0.0, + 0.5, + PricingModel::BlackScholes, + ); + assert!(metrics.atm_iv.is_finite()); + assert!(metrics.skew_slope.is_finite()); + } + + #[test] + fn term_slope_is_reasonable() { + let tenors = [0.1, 0.5, 1.0]; + let vols = [0.18, 0.20, 0.22]; + assert!(term_structure_slope(&tenors, &vols) > 0.0); + } +} diff --git a/docs/api/analysis.rst b/docs/api/analysis.rst new file mode 100644 index 0000000..a04dbe8 --- /dev/null +++ b/docs/api/analysis.rst @@ -0,0 +1,22 @@ +Analysis Modules +================ + +.. automodule:: ferro_ta.analysis.options + :members: + :undoc-members: + :show-inheritance: + +.. automodule:: ferro_ta.analysis.futures + :members: + :undoc-members: + :show-inheritance: + +.. automodule:: ferro_ta.analysis.options_strategy + :members: + :undoc-members: + :show-inheritance: + +.. automodule:: ferro_ta.analysis.derivatives_payoff + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/index.rst b/docs/api/index.rst index 18a782f..00b61ad 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -17,3 +17,4 @@ API Reference extended streaming batch + analysis diff --git a/docs/derivatives-analytics.md b/docs/derivatives-analytics.md new file mode 100644 index 0000000..95de932 --- /dev/null +++ b/docs/derivatives-analytics.md @@ -0,0 +1,70 @@ +# Derivatives Analytics + +`ferro-ta` now includes a Rust-backed derivatives analytics layer focused on +research, simulation, and risk analysis. + +## Modules + +- `ferro_ta.analysis.options` + - Black-Scholes-Merton and Black-76 pricing + - Delta, gamma, vega, theta, rho + - Implied volatility inversion with guarded Newton + bisection fallback + - IV rank / percentile / z-score + - Smile metrics: ATM IV, 25-delta risk reversal, butterfly, skew slope, convexity + - Chain helpers: moneyness labels and strike selection by offset or delta +- `ferro_ta.analysis.futures` + - Synthetic forwards and parity diagnostics + - Basis, annualized basis, implied carry, carry spread + - Continuous contract stitching: weighted, back-adjusted, ratio-adjusted + - Curve analytics: calendar spreads, slope, contango summary +- `ferro_ta.analysis.options_strategy` + - Typed strategy schemas for expiry selectors, strike selectors, multi-leg presets, + risk controls, cost assumptions, and simulation limits +- `ferro_ta.analysis.derivatives_payoff` + - Multi-leg payoff aggregation + - Portfolio-level Greeks aggregation across option and futures legs + +## Model conventions + +- `model="bsm"` expects the underlying input to be spot and `carry` to represent + a continuous dividend yield or generic carry term. +- `model="black76"` expects the underlying input to be the forward price. +- Volatility and rates use decimal units: + - `0.20` means 20% annualized volatility + - `0.05` means 5% annualized rate +- `time_to_expiry` is expressed in years. + +## Quick examples + +```python +from ferro_ta.analysis.options import greeks, implied_volatility, option_price + +price = option_price(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call") +iv = implied_volatility(price, 100.0, 100.0, 0.05, 1.0, option_type="call") +g = greeks(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call") +print(price, iv, g.delta) +``` + +```python +from ferro_ta.analysis.futures import basis, curve_summary + +print(basis(100.0, 103.0)) +print(curve_summary(100.0, [0.1, 0.5, 1.0], [101.0, 102.0, 104.0])) +``` + +```python +from ferro_ta.analysis.derivatives_payoff import PayoffLeg, strategy_payoff + +legs = [ + PayoffLeg("option", "long", option_type="call", strike=100.0, premium=5.0), + PayoffLeg("future", "long", entry_price=100.0), +] +grid = [90.0, 100.0, 110.0] +print(strategy_payoff(grid, legs=legs)) +``` + +## Notes + +- Existing `iv_rank`, `iv_percentile`, and `iv_zscore` names are preserved. +- The derivatives layer is analytics-only: there is no broker connectivity, + order routing, or execution workflow in this API. diff --git a/docs/derivatives.rst b/docs/derivatives.rst new file mode 100644 index 0000000..9ac93ef --- /dev/null +++ b/docs/derivatives.rst @@ -0,0 +1,126 @@ +Derivatives Analytics +===================== + +``ferro-ta`` includes a Rust-backed derivatives layer for analytics, research, +and simulation workflows. The implementation is analytics-only: there is no +broker connectivity, order routing, or execution engine in this package. + +What Is Included +---------------- + +Options analytics +~~~~~~~~~~~~~~~~~ + +- Rolling IV helpers: ``iv_rank``, ``iv_percentile``, ``iv_zscore`` +- Black-Scholes-Merton pricing +- Black-76 pricing +- Greeks: delta, gamma, vega, theta, rho +- Implied volatility inversion +- Smile metrics: ATM IV, 25-delta risk reversal, butterfly, skew slope, convexity +- Chain helpers: moneyness labels and strike selection by offset or delta + +Futures analytics +~~~~~~~~~~~~~~~~~ + +- Synthetic forwards and parity diagnostics +- Basis, annualized basis, implied carry, carry spread +- Continuous contract stitching: weighted, back-adjusted, ratio-adjusted +- Curve analytics: calendar spreads, slope, contango/backwardation summary + +Strategy and payoff helpers +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Typed strategy schemas for expiry selectors, strike selectors, leg presets, + risk controls, and simulation limits +- Multi-leg payoff aggregation +- Greeks aggregation across option and futures legs + +Conventions +----------- + +- ``model="bsm"`` expects spot as the underlying input. +- ``model="black76"`` expects forward as the underlying input. +- Volatility uses decimal annualized units: ``0.20`` means 20%. +- Rates and carry use decimal annualized units: ``0.05`` means 5%. +- ``time_to_expiry`` is expressed in years. + +Options Example +--------------- + +.. code-block:: python + + from ferro_ta.analysis.options import greeks, implied_volatility, option_price + + price = option_price( + 100.0, + 100.0, + 0.05, + 1.0, + 0.20, + option_type="call", + model="bsm", + ) + iv = implied_volatility( + price, + 100.0, + 100.0, + 0.05, + 1.0, + option_type="call", + model="bsm", + ) + g = greeks( + 100.0, + 100.0, + 0.05, + 1.0, + 0.20, + option_type="call", + model="bsm", + ) + +Futures Example +--------------- + +.. code-block:: python + + from ferro_ta.analysis.futures import basis, curve_summary, synthetic_forward + + front_basis = basis(100.0, 103.0) + synthetic = synthetic_forward(8.0, 5.0, 100.0, 0.02, 0.5) + curve = curve_summary(100.0, [0.1, 0.5, 1.0], [101.0, 102.0, 104.0]) + +Strategy and Payoff Example +--------------------------- + +.. code-block:: python + + from ferro_ta.analysis.derivatives_payoff import PayoffLeg, aggregate_greeks, strategy_payoff + + legs = [ + PayoffLeg( + instrument="option", + side="long", + option_type="call", + strike=100.0, + premium=5.0, + volatility=0.20, + time_to_expiry=0.5, + ), + PayoffLeg( + instrument="future", + side="long", + entry_price=100.0, + ), + ] + + payoff = strategy_payoff([90.0, 100.0, 110.0], legs=legs) + portfolio_greeks = aggregate_greeks(100.0, legs=legs) + +Related Modules +--------------- + +- :mod:`ferro_ta.analysis.options` +- :mod:`ferro_ta.analysis.futures` +- :mod:`ferro_ta.analysis.options_strategy` +- :mod:`ferro_ta.analysis.derivatives_payoff` diff --git a/docs/index.rst b/docs/index.rst index e207834..b0c14e2 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -13,6 +13,7 @@ ferro-ta Documentation streaming extended batch + derivatives benchmarks plugins changelog @@ -35,7 +36,7 @@ Features: - Math operators and transforms - Type stubs (.pyi) for IDE auto-completion - WASM binding for browser/Node.js use -- Options/IV helpers (IV rank, IV percentile, IV z-score) — see `Options/IV Helpers `_ +- Options/IV helpers and derivatives analytics — see :doc:`derivatives` - Agentic workflow and LangChain tool wrappers — see `Agentic guide `_ - MCP server for Cursor/Claude integration — see `MCP guide `_ - Sphinx documentation @@ -71,7 +72,7 @@ Further Reading - `API Stability `_ — stability tiers, versioning, and deprecation policy. - `Rust-First Policy `_ — all compute logic belongs in Rust; how to add new indicators. - `Out-of-Core Execution `_ — chunked processing and Dask integration. -- `Options/IV Helpers `_ — IV rank, IV percentile, IV z-score. +- :doc:`derivatives` — IV helpers, options pricing/Greeks/IV, futures analytics, strategy schemas, and payoff helpers. - `Agentic Workflow `_ — tools.py, workflow.py, LangChain integration. - `MCP Server `_ — run ferro-ta as an MCP server in Cursor/Claude. diff --git a/docs/options-volatility.md b/docs/options-volatility.md index fecd06a..6cdf3b9 100644 --- a/docs/options-volatility.md +++ b/docs/options-volatility.md @@ -1,101 +1,79 @@ # Options and Implied Volatility -ferro-ta provides optional helpers for implied volatility (IV) analysis -via the `ferro_ta.options` module. This document describes the scope, -data format, dependency strategy, and limitations. - ---- +`ferro-ta` exposes options analytics from `ferro_ta.analysis.options`. ## Scope -The `ferro_ta.options` module focuses on **IV series analysis**: +The module now covers both classic IV-series helpers and model-based option +analytics: -- **IV rank** — where today's IV sits relative to the min/max over a look-back window. -- **IV percentile** — fraction of observations over a look-back window at or below today's IV. -- **IV z-score** — how many standard deviations today's IV is above the rolling mean. +- `iv_rank`, `iv_percentile`, `iv_zscore` +- Black-Scholes-Merton pricing +- Black-76 pricing +- Delta, gamma, vega, theta, rho +- Implied volatility inversion +- Smile metrics and chain helpers -These functions accept any 1-D IV series (e.g. VIX daily closes, single-name -30-day IV, etc.) and return rolling statistics. +Heavy computation runs in Rust through the `_ferro_ta` extension. -**Out of scope (for now):** Black-Scholes pricing, Greeks, option chain -parsing, synthetic forward construction, dividend adjustment. For full -option-pricing functionality consider `py_vollib`, `mibian`, or similar. +## IV-series helpers ---- - -## Data format - -All functions accept a 1-D NumPy array (or any array-like) of IV values. -IV values are typically in **percentage points** (e.g. VIX = 20 means 20% -annualised volatility), but the helpers are unit-agnostic — they only -compare values within the rolling window. +The original rolling helpers remain available and keep their public names: ```python import numpy as np -from ferro_ta.options import iv_rank, iv_percentile, iv_zscore +from ferro_ta.analysis.options import iv_rank, iv_percentile, iv_zscore -# VIX-like daily close series iv = np.array([18.5, 22.3, 19.1, 25.0, 30.2, 27.8, 21.4, 19.0]) - -rank = iv_rank(iv, window=5) # rolling IV rank in [0, 1] -pct = iv_percentile(iv, window=5) # rolling IV percentile in [0, 1] -z = iv_zscore(iv, window=5) # rolling z-score +rank = iv_rank(iv, window=5) +pct = iv_percentile(iv, window=5) +z = iv_zscore(iv, window=5) ``` ---- +These helpers accept a 1-D IV series and return rolling statistics with +`NaN` during the warmup period. -## Dependency strategy +## Pricing and Greeks -The `ferro_ta.options` module uses **only NumPy** (already a core dependency). -No additional packages are required for the helpers described here. +```python +from ferro_ta.analysis.options import greeks, implied_volatility, option_price -For advanced option analytics (Black-Scholes, volatility surface -interpolation), install the optional extra: - -```bash -pip install "ferro-ta[options]" +price = option_price(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call") +iv = implied_volatility(price, 100.0, 100.0, 0.05, 1.0, option_type="call") +g = greeks(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call") ``` -This may install additional packages in the future (e.g. `py_vollib`). +Conventions: ---- +- Volatility is decimal annualized volatility: `0.20` means 20%. +- Rates are decimal annualized rates: `0.05` means 5%. +- `time_to_expiry` is measured in years. +- `model="bsm"` uses spot as the underlying input. +- `model="black76"` uses forward as the underlying input. -## API reference +## Smile and chain helpers -### `iv_rank(iv_series, window=252)` +```python +from ferro_ta.analysis.options import label_moneyness, select_strike, smile_metrics -Rolling IV rank. +strikes = [80, 90, 100, 110, 120] +vols = [0.30, 0.25, 0.20, 0.22, 0.27] -``` -rank_t = (IV_t - min(IV[t-window+1:t+1])) / (max(IV[t-window+1:t+1]) - min(IV[t-window+1:t+1])) +metrics = smile_metrics(strikes, vols, 100.0, 0.5) +labels = label_moneyness(strikes, 100.0, option_type="call") +atm = select_strike(strikes, 100.0, selector="ATM") +delta_strike = select_strike( + strikes, + 100.0, + selector="DELTA0.25", + option_type="call", + volatilities=vols, + time_to_expiry=0.5, +) ``` -Returns values in [0, 1]. NaN for the first `window - 1` bars. +## Related futures analytics -### `iv_percentile(iv_series, window=252)` - -Rolling IV percentile: fraction of the *window* bars whose IV was at or -below the current value. - -### `iv_zscore(iv_series, window=252)` - -Rolling z-score: `(IV_t - rolling_mean) / rolling_std`. - ---- - -## Limitations - -- All functions use **O(n × window)** time complexity (pure Python loops). - For large windows or series consider vectorised alternatives. -- No option chain support; the module assumes IV series as input. -- Streaming (bar-by-bar) versions of these functions are not yet - implemented. For live use, maintain a rolling buffer and call the - functions on the buffer at each bar. - ---- - -## See also - -- `ferro_ta.options` — module source. -- `ferro_ta.statistic` — general statistical functions (STDDEV, VAR, CORREL, etc.). -- `ferro_ta.volatility` — price-based volatility indicators (ATR, NATR). +See `ferro_ta.analysis.futures` and +[`docs/derivatives-analytics.md`](./derivatives-analytics.md) for synthetic +forwards, basis, carry, curve, and roll analytics. diff --git a/docs/performance.md b/docs/performance.md index 4fddcf9..684296b 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -315,10 +315,12 @@ bottlenecks are fixed or deferred. - No fast path for already 2-D C-contiguous float64 in batch_sma/ema/rsi (unlike `_to_f64` for 1-D); could avoid a potential copy. -**Options** (`python/ferro_ta/options.py`): -- `iv_rank`, `iv_percentile`, and `iv_zscore` are vectorized now, but - `iv_percentile`/`iv_zscore` still spend meaningful time in NumPy window - materialization on very long series. +**Derivatives analytics** (`python/ferro_ta/analysis/options.py`): +- `iv_rank`, `iv_percentile`, and `iv_zscore` now delegate to Rust. +- The Python layer mostly performs broadcasting and result shaping; the hot + path is in Rust. +- Model-based implied-volatility inversion is much faster now, but still more + expensive than direct pricing or Greeks due to root-finding. **Features** (`python/ferro_ta/features.py`): - `nan_policy="fill"` is vectorized now. diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 37b1338..04d9d00 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -101,3 +101,19 @@ Extended Indicators # Pivot Points pivot, r1, s1, r2, s2 = PIVOT_POINTS(high, low, close, method="classic") + +Derivatives Analytics +--------------------- + +.. code-block:: python + + from ferro_ta.analysis.options import greeks, option_price + from ferro_ta.analysis.futures import basis + + call_price = option_price(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call") + call_greeks = greeks(100.0, 100.0, 0.05, 1.0, 0.20, option_type="call") + front_basis = basis(100.0, 103.0) + +See :doc:`derivatives` for the full analytics surface, including implied +volatility inversion, smile metrics, strike selection, futures curve tools, +strategy schemas, and multi-leg payoff helpers. diff --git a/python/ferro_ta/__init__.py b/python/ferro_ta/__init__.py index 8d32d3f..7d1c3a6 100644 --- a/python/ferro_ta/__init__.py +++ b/python/ferro_ta/__init__.py @@ -11,7 +11,7 @@ Sub-packages * :mod:`ferro_ta.indicators` — All indicator functions (overlap, momentum, volume, volatility, statistic, cycle, pattern, price_transform, math_ops, extended) * :mod:`ferro_ta.core` — Core utilities (exceptions, config, logging, registry, raw) * :mod:`ferro_ta.data` — Data utilities (streaming, batch, chunked, resampling, aggregation, adapters) -* :mod:`ferro_ta.analysis` — Analysis tools (portfolio, backtest, regime, cross_asset, attribution, signals, features, crypto, options) +* :mod:`ferro_ta.analysis` — Analysis tools (portfolio, backtest, regime, cross_asset, attribution, signals, features, crypto, options, futures, derivatives payoff) * :mod:`ferro_ta.tools` — Developer tools (tools, viz, dashboard, alerts, dsl, pipeline, workflow, api_info, gpu) Sub-modules (also accessible via sub-packages above) @@ -35,6 +35,8 @@ Sub-modules (also accessible via sub-packages above) * :mod:`ferro_ta.analysis.portfolio` — Portfolio and multi-asset analytics * :mod:`ferro_ta.analysis.cross_asset` — Cross-asset and relative strength * :mod:`ferro_ta.analysis.features` — Feature matrix and ML readiness +* :mod:`ferro_ta.analysis.options` — Options pricing, Greeks, IV, smile, and chain analytics +* :mod:`ferro_ta.analysis.futures` — Futures basis, carry, roll, and curve analytics * :mod:`ferro_ta.tools.viz` — Charting and visualisation API * :mod:`ferro_ta.data.adapters` — Market data adapters diff --git a/python/ferro_ta/analysis/__init__.py b/python/ferro_ta/analysis/__init__.py index aaa5c90..ed507ea 100644 --- a/python/ferro_ta/analysis/__init__.py +++ b/python/ferro_ta/analysis/__init__.py @@ -11,7 +11,10 @@ Sub-modules * :mod:`ferro_ta.analysis.signals` — Signal composition and screening * :mod:`ferro_ta.analysis.features` — Feature matrix and ML readiness helpers * :mod:`ferro_ta.analysis.crypto` — Crypto-specific indicators and helpers -* :mod:`ferro_ta.analysis.options` — Options pricing and Greeks +* :mod:`ferro_ta.analysis.options` — Options pricing, Greeks, IV, and smile analytics +* :mod:`ferro_ta.analysis.futures` — Futures basis, curve, roll, and synthetic analytics +* :mod:`ferro_ta.analysis.options_strategy` — Typed derivatives strategy schemas +* :mod:`ferro_ta.analysis.derivatives_payoff` — Multi-leg payoff and Greeks aggregation Example usage:: diff --git a/python/ferro_ta/analysis/derivatives_payoff.py b/python/ferro_ta/analysis/derivatives_payoff.py new file mode 100644 index 0000000..2bda935 --- /dev/null +++ b/python/ferro_ta/analysis/derivatives_payoff.py @@ -0,0 +1,217 @@ +""" +ferro_ta.analysis.derivatives_payoff — Multi-leg payoff and Greeks aggregation. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from ferro_ta.analysis.options import OptionGreeks +from ferro_ta.analysis.options import greeks as option_greeks +from ferro_ta.analysis.options_strategy import DerivativesStrategy, StrategyLeg +from ferro_ta.core.exceptions import FerroTAInputError, FerroTAValueError + +__all__ = [ + "PayoffLeg", + "option_leg_payoff", + "futures_leg_payoff", + "strategy_payoff", + "aggregate_greeks", +] + + +@dataclass(frozen=True) +class PayoffLeg: + instrument: str + side: str + quantity: float = 1.0 + option_type: str | None = None + strike: float | None = None + premium: float = 0.0 + entry_price: float | None = None + volatility: float | None = None + time_to_expiry: float | None = None + rate: float = 0.0 + carry: float = 0.0 + multiplier: float = 1.0 + + def __post_init__(self) -> None: + if self.instrument not in {"option", "future"}: + raise FerroTAValueError("instrument must be 'option' or 'future'.") + if self.side not in {"long", "short"}: + raise FerroTAValueError("side must be 'long' or 'short'.") + if self.instrument == "option": + if self.option_type not in {"call", "put"}: + raise FerroTAValueError( + "option legs require option_type='call' or 'put'." + ) + if self.strike is None: + raise FerroTAValueError("option legs require strike.") + if self.instrument == "future" and self.entry_price is None: + raise FerroTAValueError("future legs require entry_price.") + + +def _side_sign(side: str) -> float: + return 1.0 if side == "long" else -1.0 + + +def _coerce_spot_grid(spot_grid: ArrayLike) -> NDArray[np.float64]: + grid = np.asarray(spot_grid, dtype=np.float64) + if grid.ndim != 1: + raise FerroTAInputError("spot_grid must be a 1-D array.") + return np.ascontiguousarray(grid) + + +def option_leg_payoff( + spot_grid: ArrayLike, + *, + strike: float, + premium: float = 0.0, + option_type: str = "call", + side: str = "long", + quantity: float = 1.0, + multiplier: float = 1.0, +) -> NDArray[np.float64]: + """Expiry payoff for a single option leg.""" + grid = _coerce_spot_grid(spot_grid) + sign = _side_sign(side) * float(quantity) * float(multiplier) + if option_type == "call": + intrinsic = np.maximum(grid - float(strike), 0.0) + elif option_type == "put": + intrinsic = np.maximum(float(strike) - grid, 0.0) + else: + raise FerroTAValueError("option_type must be 'call' or 'put'.") + return sign * (intrinsic - float(premium)) + + +def futures_leg_payoff( + spot_grid: ArrayLike, + *, + entry_price: float, + side: str = "long", + quantity: float = 1.0, + multiplier: float = 1.0, +) -> NDArray[np.float64]: + """P/L profile for a futures leg.""" + grid = _coerce_spot_grid(spot_grid) + sign = _side_sign(side) * float(quantity) * float(multiplier) + return sign * (grid - float(entry_price)) + + +def _mapping_to_leg(mapping: Mapping[str, Any]) -> PayoffLeg: + return PayoffLeg(**mapping) + + +def _strategy_leg_to_payoff_leg(leg: StrategyLeg) -> PayoffLeg: + return PayoffLeg( + instrument=leg.instrument, + side=leg.side, + quantity=float(leg.quantity), + option_type=leg.option_type, + strike=leg.strike_selector.explicit_strike, + ) + + +def _normalize_legs( + legs: Sequence[PayoffLeg | Mapping[str, Any]] | None = None, + *, + strategy: DerivativesStrategy | None = None, +) -> tuple[PayoffLeg, ...]: + if strategy is not None: + return tuple(_strategy_leg_to_payoff_leg(leg) for leg in strategy.legs) + if legs is None: + raise FerroTAInputError("Provide either legs or strategy.") + normalized: list[PayoffLeg] = [] + for leg in legs: + normalized.append(leg if isinstance(leg, PayoffLeg) else _mapping_to_leg(leg)) + return tuple(normalized) + + +def strategy_payoff( + spot_grid: ArrayLike, + *, + legs: Sequence[PayoffLeg | Mapping[str, Any]] | None = None, + strategy: DerivativesStrategy | None = None, +) -> NDArray[np.float64]: + """Aggregate expiry payoff across option and futures legs.""" + grid = _coerce_spot_grid(spot_grid) + normalized = _normalize_legs(legs, strategy=strategy) + total = np.zeros_like(grid) + for leg in normalized: + if leg.instrument == "option": + if leg.strike is None: + raise FerroTAValueError("Option payoff legs require strike.") + total += option_leg_payoff( + grid, + strike=float(leg.strike), + premium=float(leg.premium), + option_type=str(leg.option_type), + side=str(leg.side), + quantity=float(leg.quantity), + multiplier=float(leg.multiplier), + ) + else: + if leg.entry_price is None: + raise FerroTAValueError("Futures payoff legs require entry_price.") + total += futures_leg_payoff( + grid, + entry_price=float(leg.entry_price), + side=str(leg.side), + quantity=float(leg.quantity), + multiplier=float(leg.multiplier), + ) + return total + + +def aggregate_greeks( + spot: float, + *, + legs: Sequence[PayoffLeg | Mapping[str, Any]] | None = None, + strategy: DerivativesStrategy | None = None, +) -> OptionGreeks: + """Aggregate Greeks across option and futures legs.""" + normalized = _normalize_legs(legs, strategy=strategy) + totals = { + "delta": 0.0, + "gamma": 0.0, + "vega": 0.0, + "theta": 0.0, + "rho": 0.0, + } + for leg in normalized: + leg_sign = _side_sign(leg.side) * float(leg.quantity) * float(leg.multiplier) + if leg.instrument == "future": + totals["delta"] += leg_sign + continue + if leg.strike is None or leg.volatility is None or leg.time_to_expiry is None: + raise FerroTAValueError( + "Option legs require strike, volatility, and time_to_expiry for Greeks aggregation." + ) + leg_greeks = option_greeks( + float(spot), + float(leg.strike), + float(leg.rate), + float(leg.time_to_expiry), + float(leg.volatility), + option_type=str(leg.option_type), + model="bsm", + carry=float(leg.carry), + ) + totals["delta"] += leg_sign * float(leg_greeks.delta) + totals["gamma"] += leg_sign * float(leg_greeks.gamma) + totals["vega"] += leg_sign * float(leg_greeks.vega) + totals["theta"] += leg_sign * float(leg_greeks.theta) + totals["rho"] += leg_sign * float(leg_greeks.rho) + + return OptionGreeks( + totals["delta"], + totals["gamma"], + totals["vega"], + totals["theta"], + totals["rho"], + ) diff --git a/python/ferro_ta/analysis/futures.py b/python/ferro_ta/analysis/futures.py new file mode 100644 index 0000000..6b38643 --- /dev/null +++ b/python/ferro_ta/analysis/futures.py @@ -0,0 +1,230 @@ +""" +ferro_ta.analysis.futures — Futures and forward-curve analytics. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from ferro_ta._ferro_ta import annualized_basis as _rust_annualized_basis +from ferro_ta._ferro_ta import ( + back_adjusted_continuous_contract as _rust_back_adjusted, +) +from ferro_ta._ferro_ta import calendar_spreads as _rust_calendar_spreads +from ferro_ta._ferro_ta import carry_spread as _rust_carry_spread +from ferro_ta._ferro_ta import curve_slope as _rust_curve_slope +from ferro_ta._ferro_ta import curve_summary as _rust_curve_summary +from ferro_ta._ferro_ta import futures_basis as _rust_basis +from ferro_ta._ferro_ta import implied_carry_rate as _rust_implied_carry_rate +from ferro_ta._ferro_ta import parity_gap as _rust_parity_gap +from ferro_ta._ferro_ta import ( + ratio_adjusted_continuous_contract as _rust_ratio_adjusted, +) +from ferro_ta._ferro_ta import roll_yield as _rust_roll_yield +from ferro_ta._ferro_ta import synthetic_forward as _rust_synthetic_forward +from ferro_ta._ferro_ta import synthetic_spot as _rust_synthetic_spot +from ferro_ta._ferro_ta import weighted_continuous_contract as _rust_weighted +from ferro_ta._utils import _to_f64 +from ferro_ta.core.exceptions import _normalize_rust_error + +__all__ = [ + "CurveSummary", + "synthetic_forward", + "synthetic_spot", + "parity_gap", + "basis", + "annualized_basis", + "implied_carry_rate", + "carry_spread", + "weighted_continuous_contract", + "back_adjusted_continuous_contract", + "ratio_adjusted_continuous_contract", + "roll_yield", + "calendar_spreads", + "curve_slope", + "curve_summary", +] + + +@dataclass(frozen=True) +class CurveSummary: + front_basis: float + average_basis: float + slope: float + is_contango: bool + + def to_dict(self) -> dict[str, float | bool]: + return { + "front_basis": self.front_basis, + "average_basis": self.average_basis, + "slope": self.slope, + "is_contango": self.is_contango, + } + + +def synthetic_forward( + call_price: float, + put_price: float, + strike: float, + rate: float, + time_to_expiry: float, +) -> float: + return float( + _rust_synthetic_forward( + float(call_price), + float(put_price), + float(strike), + float(rate), + float(time_to_expiry), + ) + ) + + +def synthetic_spot( + call_price: float, + put_price: float, + strike: float, + rate: float, + time_to_expiry: float, + *, + carry: float = 0.0, +) -> float: + return float( + _rust_synthetic_spot( + float(call_price), + float(put_price), + float(strike), + float(rate), + float(time_to_expiry), + float(carry), + ) + ) + + +def parity_gap( + call_price: float, + put_price: float, + spot: float, + strike: float, + rate: float, + time_to_expiry: float, + *, + carry: float = 0.0, +) -> float: + return float( + _rust_parity_gap( + float(call_price), + float(put_price), + float(spot), + float(strike), + float(rate), + float(time_to_expiry), + float(carry), + ) + ) + + +def basis(spot: float, future: float) -> float: + return float(_rust_basis(float(spot), float(future))) + + +def annualized_basis(spot: float, future: float, time_to_expiry: float) -> float: + return float( + _rust_annualized_basis(float(spot), float(future), float(time_to_expiry)) + ) + + +def implied_carry_rate(spot: float, future: float, time_to_expiry: float) -> float: + return float( + _rust_implied_carry_rate(float(spot), float(future), float(time_to_expiry)) + ) + + +def carry_spread( + spot: float, future: float, rate: float, time_to_expiry: float +) -> float: + return float( + _rust_carry_spread( + float(spot), float(future), float(rate), float(time_to_expiry) + ) + ) + + +def weighted_continuous_contract( + front: ArrayLike, + next_contract: ArrayLike, + next_weights: ArrayLike, +) -> NDArray[np.float64]: + try: + return np.asarray( + _rust_weighted( + _to_f64(front), _to_f64(next_contract), _to_f64(next_weights) + ), + dtype=np.float64, + ) + except ValueError as err: + _normalize_rust_error(err) + + +def back_adjusted_continuous_contract( + front: ArrayLike, + next_contract: ArrayLike, + next_weights: ArrayLike, +) -> NDArray[np.float64]: + try: + return np.asarray( + _rust_back_adjusted( + _to_f64(front), _to_f64(next_contract), _to_f64(next_weights) + ), + dtype=np.float64, + ) + except ValueError as err: + _normalize_rust_error(err) + + +def ratio_adjusted_continuous_contract( + front: ArrayLike, + next_contract: ArrayLike, + next_weights: ArrayLike, +) -> NDArray[np.float64]: + try: + return np.asarray( + _rust_ratio_adjusted( + _to_f64(front), _to_f64(next_contract), _to_f64(next_weights) + ), + dtype=np.float64, + ) + except ValueError as err: + _normalize_rust_error(err) + + +def roll_yield(front_price: float, next_price: float, time_to_expiry: float) -> float: + return float( + _rust_roll_yield(float(front_price), float(next_price), float(time_to_expiry)) + ) + + +def calendar_spreads(futures_prices: ArrayLike) -> NDArray[np.float64]: + return np.asarray(_rust_calendar_spreads(_to_f64(futures_prices)), dtype=np.float64) + + +def curve_slope(tenors: ArrayLike, futures_prices: ArrayLike) -> float: + try: + return float(_rust_curve_slope(_to_f64(tenors), _to_f64(futures_prices))) + except ValueError as err: + _normalize_rust_error(err) + + +def curve_summary( + spot: float, tenors: ArrayLike, futures_prices: ArrayLike +) -> CurveSummary: + try: + front_basis, average_basis, slope, is_contango = _rust_curve_summary( + float(spot), _to_f64(tenors), _to_f64(futures_prices) + ) + except ValueError as err: + _normalize_rust_error(err) + return CurveSummary(front_basis, average_basis, slope, is_contango) diff --git a/python/ferro_ta/analysis/options.py b/python/ferro_ta/analysis/options.py index 44327e9..10ee640 100644 --- a/python/ferro_ta/analysis/options.py +++ b/python/ferro_ta/analysis/options.py @@ -1,206 +1,632 @@ """ -ferro_ta.options — Options and Implied Volatility Helpers -========================================================= +ferro_ta.analysis.options — Rust-backed derivatives analytics for options. -Optional module that provides helpers for options/IV analysis when supplied -with an implied-volatility series (IV series as input). All heavy compute -delegates to Rust via ``ferro_ta`` core; this module is a thin orchestration -layer. - -.. note:: - Options support is **optional** and does not require any additional - third-party libraries beyond ``numpy``. For advanced option-pricing - functionality (e.g. Black-Scholes, Greeks) install the optional - ``ferro_ta[options]`` extra which may pull in additional dependencies. - -See ``docs/options-volatility.md`` for the full design doc. - -Quick start ------------ ->>> import numpy as np ->>> from ferro_ta.analysis.options import iv_rank, iv_percentile ->>> ->>> # Synthetic IV series (e.g. VIX or single-name IV) ->>> rng = np.random.default_rng(42) ->>> iv = rng.uniform(10, 40, 252) ->>> ->>> rank = iv_rank(iv, window=252) ->>> pct = iv_percentile(iv, window=252) - -API ---- -iv_rank(iv_series, window) - Rolling IV rank: where is today's IV relative to min/max over *window* bars? - Returns values in [0, 1] (NaN during warm-up). - -iv_percentile(iv_series, window) - Rolling IV percentile: fraction of observations over *window* bars that are - ≤ today's IV. Returns values in [0, 1] (NaN during warm-up). - -iv_zscore(iv_series, window) - Rolling IV z-score: (IV - rolling_mean) / rolling_std over *window* bars. - Returns z-score values (NaN during warm-up). +This module preserves the legacy IV-series helpers and expands them with +pricing, Greeks, implied-volatility inversion, smile analytics, and strike +selection helpers suitable for research and simulation workflows. """ from __future__ import annotations +from dataclasses import dataclass +from typing import TypeAlias + import numpy as np -from numpy.lib.stride_tricks import sliding_window_view from numpy.typing import ArrayLike, NDArray -from ferro_ta.core.exceptions import FerroTAInputError, FerroTAValueError +from ferro_ta._ferro_ta import ( + black76_price as _rust_black76_price, +) +from ferro_ta._ferro_ta import ( + black76_price_batch as _rust_black76_price_batch, +) +from ferro_ta._ferro_ta import ( + bsm_price as _rust_bsm_price, +) +from ferro_ta._ferro_ta import ( + bsm_price_batch as _rust_bsm_price_batch, +) +from ferro_ta._ferro_ta import ( + implied_volatility as _rust_implied_volatility, +) +from ferro_ta._ferro_ta import ( + implied_volatility_batch as _rust_implied_volatility_batch, +) +from ferro_ta._ferro_ta import ( + iv_percentile as _rust_iv_percentile, +) +from ferro_ta._ferro_ta import ( + iv_rank as _rust_iv_rank, +) +from ferro_ta._ferro_ta import ( + iv_zscore as _rust_iv_zscore, +) +from ferro_ta._ferro_ta import ( + moneyness_labels as _rust_moneyness_labels, +) +from ferro_ta._ferro_ta import ( + option_greeks as _rust_option_greeks, +) +from ferro_ta._ferro_ta import ( + option_greeks_batch as _rust_option_greeks_batch, +) +from ferro_ta._ferro_ta import ( + select_strike_delta as _rust_select_strike_delta, +) +from ferro_ta._ferro_ta import ( + select_strike_offset as _rust_select_strike_offset, +) +from ferro_ta._ferro_ta import ( + smile_metrics as _rust_smile_metrics, +) +from ferro_ta._ferro_ta import ( + term_structure_slope as _rust_term_structure_slope, +) +from ferro_ta._utils import _to_f64 +from ferro_ta.core.exceptions import ( + FerroTAInputError, + FerroTAValueError, + _normalize_rust_error, +) + +ScalarOrArray: TypeAlias = float | NDArray[np.float64] __all__ = [ + "OptionGreeks", + "SmileMetrics", + "black_scholes_price", + "black_76_price", + "option_price", + "greeks", + "implied_volatility", + "smile_metrics", + "term_structure_slope", + "label_moneyness", + "select_strike", "iv_rank", "iv_percentile", "iv_zscore", ] -def _validate_iv(iv_series: NDArray[np.float64], window: int) -> NDArray[np.float64]: - """Validate and convert iv_series; check window.""" - arr = np.asarray(iv_series, dtype=np.float64) - if arr.ndim != 1: - raise FerroTAInputError("iv_series must be a 1-D array.") +@dataclass(frozen=True) +class OptionGreeks: + """Container for first-order Greeks.""" + + delta: ScalarOrArray + gamma: ScalarOrArray + vega: ScalarOrArray + theta: ScalarOrArray + rho: ScalarOrArray + + def to_dict(self) -> dict[str, ScalarOrArray]: + return { + "delta": self.delta, + "gamma": self.gamma, + "vega": self.vega, + "theta": self.theta, + "rho": self.rho, + } + + +@dataclass(frozen=True) +class SmileMetrics: + """Summary metrics for a single smile slice.""" + + atm_iv: float + risk_reversal_25d: float + butterfly_25d: float + skew_slope: float + convexity: float + + def to_dict(self) -> dict[str, float]: + return { + "atm_iv": self.atm_iv, + "risk_reversal_25d": self.risk_reversal_25d, + "butterfly_25d": self.butterfly_25d, + "skew_slope": self.skew_slope, + "convexity": self.convexity, + } + + +def _validate_option_type(option_type: str) -> str: + value = option_type.lower() + if value not in {"call", "put"}: + raise FerroTAValueError("option_type must be 'call' or 'put'.") + return value + + +def _validate_model(model: str) -> str: + value = model.lower() + aliases = { + "bsm": "bsm", + "black_scholes": "bsm", + "black-scholes": "bsm", + "blackscholes": "bsm", + "black76": "black76", + "black_76": "black76", + "black-76": "black76", + } + if value not in aliases: + raise FerroTAValueError( + "model must be one of 'bsm', 'black_scholes', or 'black76'." + ) + return aliases[value] + + +def _coerce_1d(data: ArrayLike | float, *, name: str) -> tuple[np.ndarray, bool]: + arr = np.asarray(data, dtype=np.float64) + if arr.ndim > 1: + raise FerroTAInputError(f"{name} must be a scalar or 1-D array.") + return np.ascontiguousarray(arr.reshape(-1)), arr.ndim == 0 + + +def _broadcast_inputs( + **kwargs: ArrayLike | float, +) -> tuple[dict[str, np.ndarray], bool]: + arrays: dict[str, np.ndarray] = {} + scalar_flags: list[bool] = [] + for name, value in kwargs.items(): + arr, is_scalar = _coerce_1d(value, name=name) + arrays[name] = arr + scalar_flags.append(is_scalar) + try: + broadcast = np.broadcast_arrays(*arrays.values()) + except ValueError as err: + raise FerroTAInputError( + f"Inputs could not be broadcast together: {', '.join(arrays.keys())}" + ) from err + out = { + name: np.ascontiguousarray(arr, dtype=np.float64).reshape(-1) + for name, arr in zip(arrays.keys(), broadcast) + } + return out, all(scalar_flags) + + +def _result_or_scalar(result: np.ndarray, scalar_mode: bool) -> ScalarOrArray: + return float(result[0]) if scalar_mode else result + + +def iv_rank(iv_series: ArrayLike, window: int = 252) -> NDArray[np.float64]: + """Compute rolling IV rank in Rust while preserving the legacy API.""" + try: + arr = _to_f64(iv_series) + except ValueError as err: + raise FerroTAInputError(str(err)) from err if len(arr) == 0: raise FerroTAInputError("iv_series must not be empty.") if window < 1: raise FerroTAValueError(f"window must be >= 1, got {window}.") - return arr + try: + return np.asarray(_rust_iv_rank(arr, int(window)), dtype=np.float64) + except ValueError as err: + _normalize_rust_error(err) -def iv_rank( - iv_series: ArrayLike, - window: int = 252, -) -> NDArray[np.float64]: - """Compute rolling IV rank. - - IV rank measures where today's IV sits relative to the min/max of IV over - the look-back *window*. A value of 1.0 means current IV is at its - highest, 0.0 means it is at its lowest. - - Parameters - ---------- - iv_series : array-like - 1-D series of implied volatility values (e.g. VIX daily closes or - single-name option IV). Any positive numeric values are accepted. - window : int - Look-back period in bars (default 252 ≈ 1 trading year). - - Returns - ------- - ndarray of float64 - Rolling IV rank in [0, 1]. NaN for bars where the window is not yet - full (i.e. the first ``window - 1`` bars). - - Examples - -------- - >>> import numpy as np - >>> from ferro_ta.analysis.options import iv_rank - >>> iv = np.array([20.0, 25.0, 30.0, 15.0, 22.0]) - >>> iv_rank(iv, window=3) - array([ nan, nan, 1. , 0. , 0.46666667]) - """ - arr = _validate_iv(np.asarray(iv_series, dtype=np.float64), window) - n = len(arr) - out = np.full(n, np.nan, dtype=np.float64) - if window > n: - return out - - windows = sliding_window_view(arr, window_shape=window) - lower = np.nanmin(windows, axis=1) - upper = np.nanmax(windows, axis=1) - current = arr[window - 1 :] - spread = upper - lower - out[window - 1 :] = np.where(spread == 0.0, 0.0, (current - lower) / spread) - - return out +def iv_percentile(iv_series: ArrayLike, window: int = 252) -> NDArray[np.float64]: + """Compute rolling IV percentile in Rust while preserving the legacy API.""" + try: + arr = _to_f64(iv_series) + except ValueError as err: + raise FerroTAInputError(str(err)) from err + if len(arr) == 0: + raise FerroTAInputError("iv_series must not be empty.") + if window < 1: + raise FerroTAValueError(f"window must be >= 1, got {window}.") + try: + return np.asarray(_rust_iv_percentile(arr, int(window)), dtype=np.float64) + except ValueError as err: + _normalize_rust_error(err) -def iv_percentile( - iv_series: ArrayLike, - window: int = 252, -) -> NDArray[np.float64]: - """Compute rolling IV percentile. - - IV percentile measures the fraction of days over the look-back *window* - for which IV was *at or below* today's level. Unlike IV rank (which only - considers min/max), IV percentile uses the full distribution of values. - - Parameters - ---------- - iv_series : array-like - 1-D series of implied volatility values. - window : int - Look-back period in bars (default 252). - - Returns - ------- - ndarray of float64 - Rolling IV percentile in [0, 1]. NaN for bars before the window fills. - - Examples - -------- - >>> import numpy as np - >>> from ferro_ta.analysis.options import iv_percentile - >>> iv = np.array([20.0, 25.0, 30.0, 15.0, 22.0]) - >>> iv_percentile(iv, window=3) - array([ nan, nan, 1. , 0. , 0.33333333]) - """ - arr = _validate_iv(np.asarray(iv_series, dtype=np.float64), window) - n = len(arr) - out = np.full(n, np.nan, dtype=np.float64) - if window > n: - return out - - windows = sliding_window_view(arr, window_shape=window) - current = arr[window - 1 :, None] - out[window - 1 :] = np.sum(windows <= current, axis=1, dtype=np.int64) / window - - return out +def iv_zscore(iv_series: ArrayLike, window: int = 252) -> NDArray[np.float64]: + """Compute rolling IV z-score in Rust while preserving the legacy API.""" + try: + arr = _to_f64(iv_series) + except ValueError as err: + raise FerroTAInputError(str(err)) from err + if len(arr) == 0: + raise FerroTAInputError("iv_series must not be empty.") + if window < 1: + raise FerroTAValueError(f"window must be >= 1, got {window}.") + try: + return np.asarray(_rust_iv_zscore(arr, int(window)), dtype=np.float64) + except ValueError as err: + _normalize_rust_error(err) -def iv_zscore( - iv_series: ArrayLike, - window: int = 252, -) -> NDArray[np.float64]: - """Compute rolling IV z-score. +def black_scholes_price( + spot: ArrayLike | float, + strike: ArrayLike | float, + rate: ArrayLike | float, + time_to_expiry: ArrayLike | float, + volatility: ArrayLike | float, + *, + option_type: str = "call", + dividend_yield: ArrayLike | float = 0.0, +) -> ScalarOrArray: + """Price options under Black-Scholes-Merton.""" + option_type = _validate_option_type(option_type) + arrays, scalar_mode = _broadcast_inputs( + spot=spot, + strike=strike, + rate=rate, + time_to_expiry=time_to_expiry, + volatility=volatility, + dividend_yield=dividend_yield, + ) + try: + if scalar_mode: + return float( + _rust_bsm_price( + float(arrays["spot"][0]), + float(arrays["strike"][0]), + float(arrays["rate"][0]), + float(arrays["time_to_expiry"][0]), + float(arrays["volatility"][0]), + option_type, + float(arrays["dividend_yield"][0]), + ) + ) + out = _rust_bsm_price_batch( + arrays["spot"], + arrays["strike"], + arrays["rate"], + arrays["time_to_expiry"], + arrays["volatility"], + arrays["dividend_yield"], + option_type, + ) + return np.asarray(out, dtype=np.float64) + except ValueError as err: + _normalize_rust_error(err) - Measures how many standard deviations today's IV is above (positive) or - below (negative) the rolling mean over *window* bars. - Parameters - ---------- - iv_series : array-like - 1-D series of implied volatility values. - window : int - Look-back period in bars (default 252). +def black_76_price( + forward: ArrayLike | float, + strike: ArrayLike | float, + rate: ArrayLike | float, + time_to_expiry: ArrayLike | float, + volatility: ArrayLike | float, + *, + option_type: str = "call", +) -> ScalarOrArray: + """Price options under Black-76.""" + option_type = _validate_option_type(option_type) + arrays, scalar_mode = _broadcast_inputs( + forward=forward, + strike=strike, + rate=rate, + time_to_expiry=time_to_expiry, + volatility=volatility, + ) + try: + if scalar_mode: + return float( + _rust_black76_price( + float(arrays["forward"][0]), + float(arrays["strike"][0]), + float(arrays["rate"][0]), + float(arrays["time_to_expiry"][0]), + float(arrays["volatility"][0]), + option_type, + ) + ) + out = _rust_black76_price_batch( + arrays["forward"], + arrays["strike"], + arrays["rate"], + arrays["time_to_expiry"], + arrays["volatility"], + option_type, + ) + return np.asarray(out, dtype=np.float64) + except ValueError as err: + _normalize_rust_error(err) - Returns - ------- - ndarray of float64 - Rolling z-score. NaN during warm-up (first ``window - 1`` bars) and - when the rolling standard deviation is zero. - Examples - -------- - >>> import numpy as np - >>> from ferro_ta.analysis.options import iv_zscore - >>> iv = np.array([20.0, 25.0, 30.0, 15.0, 22.0]) - >>> z = iv_zscore(iv, window=3) - >>> z[2] # (30 - 25) / std([20, 25, 30]) - np.float64(1.2247...) - """ - arr = _validate_iv(np.asarray(iv_series, dtype=np.float64), window) - n = len(arr) - out = np.full(n, np.nan, dtype=np.float64) - if window > n: - return out +def option_price( + underlying: ArrayLike | float, + strike: ArrayLike | float, + rate: ArrayLike | float, + time_to_expiry: ArrayLike | float, + volatility: ArrayLike | float, + *, + option_type: str = "call", + model: str = "bsm", + carry: ArrayLike | float = 0.0, +) -> ScalarOrArray: + """Model-dispatched option price helper.""" + model = _validate_model(model) + if model == "black76": + return black_76_price( + underlying, + strike, + rate, + time_to_expiry, + volatility, + option_type=option_type, + ) + return black_scholes_price( + underlying, + strike, + rate, + time_to_expiry, + volatility, + option_type=option_type, + dividend_yield=carry, + ) - windows = sliding_window_view(arr, window_shape=window) - mean = np.nanmean(windows, axis=1) - std = np.nanstd(windows, axis=1, ddof=0) - current = arr[window - 1 :] - out[window - 1 :] = np.where(std == 0.0, np.nan, (current - mean) / std) - return out +def greeks( + underlying: ArrayLike | float, + strike: ArrayLike | float, + rate: ArrayLike | float, + time_to_expiry: ArrayLike | float, + volatility: ArrayLike | float, + *, + option_type: str = "call", + model: str = "bsm", + carry: ArrayLike | float = 0.0, +) -> OptionGreeks: + """Return delta, gamma, vega, theta, and rho.""" + option_type = _validate_option_type(option_type) + model = _validate_model(model) + arrays, scalar_mode = _broadcast_inputs( + underlying=underlying, + strike=strike, + rate=rate, + time_to_expiry=time_to_expiry, + volatility=volatility, + carry=carry, + ) + try: + if scalar_mode: + delta, gamma, vega, theta, rho = _rust_option_greeks( + float(arrays["underlying"][0]), + float(arrays["strike"][0]), + float(arrays["rate"][0]), + float(arrays["time_to_expiry"][0]), + float(arrays["volatility"][0]), + option_type, + model, + float(arrays["carry"][0]), + ) + return OptionGreeks(delta, gamma, vega, theta, rho) + + delta, gamma, vega, theta, rho = _rust_option_greeks_batch( + arrays["underlying"], + arrays["strike"], + arrays["rate"], + arrays["time_to_expiry"], + arrays["volatility"], + option_type, + model, + arrays["carry"], + ) + return OptionGreeks( + np.asarray(delta, dtype=np.float64), + np.asarray(gamma, dtype=np.float64), + np.asarray(vega, dtype=np.float64), + np.asarray(theta, dtype=np.float64), + np.asarray(rho, dtype=np.float64), + ) + except ValueError as err: + _normalize_rust_error(err) + + +def implied_volatility( + price: ArrayLike | float, + underlying: ArrayLike | float, + strike: ArrayLike | float, + rate: ArrayLike | float, + time_to_expiry: ArrayLike | float, + *, + option_type: str = "call", + model: str = "bsm", + carry: ArrayLike | float = 0.0, + initial_guess: ArrayLike | float = 0.2, + tolerance: float = 1e-8, + max_iterations: int = 100, +) -> ScalarOrArray: + """Invert option prices to implied volatility.""" + option_type = _validate_option_type(option_type) + model = _validate_model(model) + arrays, scalar_mode = _broadcast_inputs( + price=price, + underlying=underlying, + strike=strike, + rate=rate, + time_to_expiry=time_to_expiry, + carry=carry, + initial_guess=initial_guess, + ) + try: + if scalar_mode: + return float( + _rust_implied_volatility( + float(arrays["price"][0]), + float(arrays["underlying"][0]), + float(arrays["strike"][0]), + float(arrays["rate"][0]), + float(arrays["time_to_expiry"][0]), + option_type, + model, + float(arrays["carry"][0]), + float(arrays["initial_guess"][0]), + float(tolerance), + int(max_iterations), + ) + ) + out = _rust_implied_volatility_batch( + arrays["price"], + arrays["underlying"], + arrays["strike"], + arrays["rate"], + arrays["time_to_expiry"], + option_type, + model, + arrays["carry"], + arrays["initial_guess"], + float(tolerance), + int(max_iterations), + ) + return np.asarray(out, dtype=np.float64) + except ValueError as err: + _normalize_rust_error(err) + + +def smile_metrics( + strikes: ArrayLike, + vols: ArrayLike, + reference_price: float, + time_to_expiry: float, + *, + model: str = "bsm", + rate: float = 0.0, + carry: float = 0.0, +) -> SmileMetrics: + """Compute ATM IV, 25-delta RR/BF, skew slope, and convexity.""" + model = _validate_model(model) + strikes_arr = _to_f64(strikes) + vols_arr = _to_f64(vols) + order = np.argsort(strikes_arr) + strikes_arr = strikes_arr[order] + vols_arr = vols_arr[order] + try: + atm_iv, rr25, bf25, slope, convexity = _rust_smile_metrics( + strikes_arr, + vols_arr, + float(reference_price), + float(time_to_expiry), + model, + float(rate), + float(carry), + ) + except ValueError as err: + _normalize_rust_error(err) + return SmileMetrics(atm_iv, rr25, bf25, slope, convexity) + + +def term_structure_slope(tenors: ArrayLike, atm_ivs: ArrayLike) -> float: + """Slope of ATM IV against tenor.""" + try: + return float(_rust_term_structure_slope(_to_f64(tenors), _to_f64(atm_ivs))) + except ValueError as err: + _normalize_rust_error(err) + + +def label_moneyness( + strikes: ArrayLike, + reference_price: float, + *, + option_type: str = "call", +) -> NDArray[np.object_]: + """Label strikes as ``ITM``, ``ATM``, or ``OTM``.""" + option_type = _validate_option_type(option_type) + try: + codes = np.asarray( + _rust_moneyness_labels( + _to_f64(strikes), float(reference_price), option_type + ), + dtype=np.int8, + ) + except ValueError as err: + _normalize_rust_error(err) + mapping = np.array(["OTM", "ATM", "ITM"], dtype=object) + return mapping[codes + 1] + + +def _parse_selector_steps(selector: str) -> int: + suffix = selector[3:] + if suffix == "": + return 1 + try: + return int(suffix) + except ValueError as err: + raise FerroTAValueError( + f"Could not parse strike selector '{selector}'. Expected forms like ATM, ITM1, OTM2." + ) from err + + +def select_strike( + strikes: ArrayLike, + reference_price: float, + *, + option_type: str = "call", + selector: str = "ATM", + delta_target: float | None = None, + volatilities: ArrayLike | None = None, + time_to_expiry: float | None = None, + model: str = "bsm", + rate: float = 0.0, + carry: float = 0.0, +) -> float | None: + """Select a strike by ATM/ITM/OTM offset or delta target.""" + option_type = _validate_option_type(option_type) + model = _validate_model(model) + strikes_arr = _to_f64(strikes) + + if len(strikes_arr) == 0: + raise FerroTAInputError("strikes must not be empty.") + + selector_norm = selector.strip().upper() + if delta_target is None and selector_norm.startswith("DELTA"): + try: + delta_target = float(selector_norm.replace("DELTA", "")) + except ValueError as err: + raise FerroTAValueError( + f"Could not parse delta selector '{selector}'. Example: selector='DELTA0.25'." + ) from err + + if delta_target is not None: + if volatilities is None or time_to_expiry is None: + raise FerroTAValueError( + "Delta-based strike selection requires volatilities and time_to_expiry." + ) + vols_arr = _to_f64(volatilities) + if len(vols_arr) != len(strikes_arr): + raise FerroTAInputError( + "strikes and volatilities must have the same length." + ) + order = np.argsort(strikes_arr) + strikes_arr = strikes_arr[order] + vols_arr = vols_arr[order] + try: + strike = _rust_select_strike_delta( + strikes_arr, + vols_arr, + float(reference_price), + float(time_to_expiry), + float(delta_target), + option_type, + model, + float(rate), + float(carry), + ) + except ValueError as err: + _normalize_rust_error(err) + return None if strike is None else float(strike) + + order = np.argsort(strikes_arr) + sorted_strikes = strikes_arr[order] + if selector_norm == "ATM": + offset = 0 + elif selector_norm.startswith("ITM"): + steps = _parse_selector_steps(selector_norm) + offset = -steps if option_type == "call" else steps + elif selector_norm.startswith("OTM"): + steps = _parse_selector_steps(selector_norm) + offset = steps if option_type == "call" else -steps + else: + raise FerroTAValueError( + f"Unsupported selector '{selector}'. Use ATM, ITM, OTM, or DELTA." + ) + + try: + strike = _rust_select_strike_offset( + sorted_strikes, float(reference_price), int(offset) + ) + except ValueError as err: + _normalize_rust_error(err) + return None if strike is None else float(strike) diff --git a/python/ferro_ta/analysis/options_strategy.py b/python/ferro_ta/analysis/options_strategy.py new file mode 100644 index 0000000..21978f2 --- /dev/null +++ b/python/ferro_ta/analysis/options_strategy.py @@ -0,0 +1,317 @@ +""" +ferro_ta.analysis.options_strategy — Typed strategy parameter schemas. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +from datetime import date +from enum import Enum +from typing import Any + +from ferro_ta.core.exceptions import FerroTAInputError, FerroTAValueError + +__all__ = [ + "ExpirySelectorKind", + "StrikeSelectorKind", + "LegPreset", + "RiskMode", + "ExpirySelector", + "StrikeSelector", + "RiskControl", + "SimulationLimits", + "StrategyLeg", + "DerivativesStrategy", + "build_strategy_preset", +] + + +class ExpirySelectorKind(str, Enum): + CURRENT_WEEK = "current_week" + NEXT_WEEK = "next_week" + CURRENT_MONTH = "current_month" + NEXT_MONTH = "next_month" + EXPLICIT_DATE = "explicit_date" + + +class StrikeSelectorKind(str, Enum): + ATM = "atm" + ITM = "itm" + OTM = "otm" + DELTA = "delta" + EXPLICIT = "explicit" + + +class LegPreset(str, Enum): + STRADDLE = "straddle" + STRANGLE = "strangle" + IRON_CONDOR = "iron_condor" + BULL_CALL_SPREAD = "bull_call_spread" + BEAR_PUT_SPREAD = "bear_put_spread" + CUSTOM = "custom" + + +class RiskMode(str, Enum): + PER_LEG = "per_leg" + COMBINED_PNL = "combined_pnl" + + +@dataclass(frozen=True) +class ExpirySelector: + kind: ExpirySelectorKind | str + explicit_date: date | None = None + + def __post_init__(self) -> None: + kind = ExpirySelectorKind(self.kind) + object.__setattr__(self, "kind", kind) + if kind is ExpirySelectorKind.EXPLICIT_DATE and self.explicit_date is None: + raise FerroTAValueError( + "ExpirySelector(kind='explicit_date') requires explicit_date." + ) + if ( + kind is not ExpirySelectorKind.EXPLICIT_DATE + and self.explicit_date is not None + ): + raise FerroTAValueError( + "explicit_date is only valid when kind='explicit_date'." + ) + + +@dataclass(frozen=True) +class StrikeSelector: + kind: StrikeSelectorKind | str + steps: int = 0 + delta: float | None = None + explicit_strike: float | None = None + + def __post_init__(self) -> None: + kind = StrikeSelectorKind(self.kind) + object.__setattr__(self, "kind", kind) + if self.steps < 0: + raise FerroTAValueError("steps must be >= 0.") + if kind is StrikeSelectorKind.DELTA and self.delta is None: + raise FerroTAValueError( + "StrikeSelector(kind='delta') requires a delta target." + ) + if self.delta is not None and not (0.0 < float(self.delta) < 1.0): + raise FerroTAValueError("delta must be in the open interval (0, 1).") + if kind is StrikeSelectorKind.EXPLICIT and self.explicit_strike is None: + raise FerroTAValueError( + "StrikeSelector(kind='explicit') requires explicit_strike." + ) + + +@dataclass(frozen=True) +class RiskControl: + stop_loss_type: str | None = None + stop_loss_value: float | None = None + target_type: str | None = None + target_value: float | None = None + trailstop_type: str | None = None + trailstop_value: float | None = None + breakeven_trigger: float | None = None + + def __post_init__(self) -> None: + for name in ( + "stop_loss_value", + "target_value", + "trailstop_value", + "breakeven_trigger", + ): + value = getattr(self, name) + if value is not None and float(value) < 0.0: + raise FerroTAValueError(f"{name} must be >= 0.") + + +@dataclass(frozen=True) +class SimulationLimits: + max_premium_outlay: float | None = None + max_loss_per_trade: float | None = None + daily_max_drawdown: float | None = None + cooldown_bars: int = 0 + reentry_allowed: bool = True + + def __post_init__(self) -> None: + for name in ( + "max_premium_outlay", + "max_loss_per_trade", + "daily_max_drawdown", + ): + value = getattr(self, name) + if value is not None and float(value) < 0.0: + raise FerroTAValueError(f"{name} must be >= 0.") + if self.cooldown_bars < 0: + raise FerroTAValueError("cooldown_bars must be >= 0.") + + +@dataclass(frozen=True) +class StrategyLeg: + underlying: str + expiry_selector: ExpirySelector + strike_selector: StrikeSelector + option_type: str + side: str = "long" + quantity: int = 1 + instrument: str = "option" + premium_limit: float | None = None + + def __post_init__(self) -> None: + if self.underlying.strip() == "": + raise FerroTAInputError("underlying must not be empty.") + if self.option_type not in {"call", "put"}: + raise FerroTAValueError("option_type must be 'call' or 'put'.") + if self.side not in {"long", "short"}: + raise FerroTAValueError("side must be 'long' or 'short'.") + if self.instrument not in {"option", "future"}: + raise FerroTAValueError("instrument must be 'option' or 'future'.") + if self.quantity == 0: + raise FerroTAValueError("quantity must be non-zero.") + if self.premium_limit is not None and self.premium_limit < 0.0: + raise FerroTAValueError("premium_limit must be >= 0.") + + +@dataclass(frozen=True) +class DerivativesStrategy: + name: str + preset: LegPreset | str = LegPreset.CUSTOM + legs: tuple[StrategyLeg, ...] = field(default_factory=tuple) + risk_controls: RiskControl = field(default_factory=RiskControl) + risk_mode: RiskMode | str = RiskMode.COMBINED_PNL + commission: float = 0.0 + slippage: float = 0.0 + spread_assumption: float = 0.0 + limits: SimulationLimits = field(default_factory=SimulationLimits) + + def __post_init__(self) -> None: + preset = LegPreset(self.preset) + risk_mode = RiskMode(self.risk_mode) + object.__setattr__(self, "preset", preset) + object.__setattr__(self, "risk_mode", risk_mode) + if self.name.strip() == "": + raise FerroTAInputError("name must not be empty.") + if len(self.legs) == 0: + raise FerroTAInputError("legs must contain at least one strategy leg.") + for cost_name in ("commission", "slippage", "spread_assumption"): + if float(getattr(self, cost_name)) < 0.0: + raise FerroTAValueError(f"{cost_name} must be >= 0.") + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def build_strategy_preset( + preset: LegPreset | str, + *, + name: str, + underlying: str, + expiry_selector: ExpirySelector, + base_strike_selector: StrikeSelector | None = None, + risk_controls: RiskControl | None = None, + risk_mode: RiskMode | str = RiskMode.COMBINED_PNL, + commission: float = 0.0, + slippage: float = 0.0, + spread_assumption: float = 0.0, + limits: SimulationLimits | None = None, +) -> DerivativesStrategy: + """Build a common research preset using typed leg definitions.""" + preset = LegPreset(preset) + risk_controls = risk_controls or RiskControl() + limits = limits or SimulationLimits() + atm = base_strike_selector or StrikeSelector(StrikeSelectorKind.ATM) + + if preset is LegPreset.CUSTOM: + raise FerroTAValueError( + "build_strategy_preset does not construct CUSTOM presets." + ) + + legs: tuple[StrategyLeg, ...] + + if preset is LegPreset.STRADDLE: + legs = ( + StrategyLeg(underlying, expiry_selector, atm, "call", "long"), + StrategyLeg(underlying, expiry_selector, atm, "put", "long"), + ) + elif preset is LegPreset.STRANGLE: + legs = ( + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=1), + "call", + "long", + ), + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=1), + "put", + "long", + ), + ) + elif preset is LegPreset.BULL_CALL_SPREAD: + legs = ( + StrategyLeg(underlying, expiry_selector, atm, "call", "long"), + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=1), + "call", + "short", + ), + ) + elif preset is LegPreset.BEAR_PUT_SPREAD: + legs = ( + StrategyLeg(underlying, expiry_selector, atm, "put", "long"), + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=1), + "put", + "short", + ), + ) + elif preset is LegPreset.IRON_CONDOR: + legs = ( + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=1), + "put", + "short", + ), + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=2), + "put", + "long", + ), + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=1), + "call", + "short", + ), + StrategyLeg( + underlying, + expiry_selector, + StrikeSelector(StrikeSelectorKind.OTM, steps=2), + "call", + "long", + ), + ) + else: + raise FerroTAValueError(f"Unsupported preset '{preset.value}'.") + + return DerivativesStrategy( + name=name, + preset=preset, + legs=legs, + risk_controls=risk_controls, + risk_mode=risk_mode, + commission=commission, + slippage=slippage, + spread_assumption=spread_assumption, + limits=limits, + ) diff --git a/python/ferro_ta/data/batch.py b/python/ferro_ta/data/batch.py index f31e92b..8e8d6c2 100644 --- a/python/ferro_ta/data/batch.py +++ b/python/ferro_ta/data/batch.py @@ -29,7 +29,7 @@ Usage from __future__ import annotations -from collections.abc import Callable +from collections.abc import Callable, Sequence import numpy as np from numpy.typing import ArrayLike @@ -120,7 +120,9 @@ def _extract_timeperiod( def compute_many( - indicators: list[str | tuple[str, dict[str, object]] | tuple[str, dict[str, object], object]], + indicators: Sequence[ + str | tuple[str, dict[str, object]] | tuple[str, dict[str, object], object] + ], *, close: ArrayLike, high: ArrayLike | None = None, @@ -138,7 +140,9 @@ def compute_many( close_arr = np.ascontiguousarray(close, dtype=np.float64) high_arr = None if high is None else np.ascontiguousarray(high, dtype=np.float64) low_arr = None if low is None else np.ascontiguousarray(low, dtype=np.float64) - volume_arr = None if volume is None else np.ascontiguousarray(volume, dtype=np.float64) + volume_arr = ( + None if volume is None else np.ascontiguousarray(volume, dtype=np.float64) + ) normalized = [_normalize_indicator_spec(spec) for spec in indicators] results: list[object | None] = [None] * len(normalized) @@ -161,11 +165,7 @@ def compute_many( continue hlc_period = _extract_timeperiod(name, kwargs, _HLC_FASTPATH_DEFAULTS) - if ( - hlc_period is not None - and high_arr is not None - and low_arr is not None - ): + if hlc_period is not None and high_arr is not None and low_arr is not None: hlc_indices.append(idx) hlc_names.append(name) hlc_periods.append(hlc_period) @@ -196,7 +196,9 @@ def compute_many( if high_arr is not None and low_arr is not None: try: - results[idx] = _registry_run(name, high_arr, low_arr, close_arr, **kwargs) + results[idx] = _registry_run( + name, high_arr, low_arr, close_arr, **kwargs + ) continue except Exception: pass diff --git a/src/futures/basis.rs b/src/futures/basis.rs new file mode 100644 index 0000000..2175d5b --- /dev/null +++ b/src/futures/basis.rs @@ -0,0 +1,34 @@ +use pyo3::prelude::*; + +#[pyfunction] +pub fn futures_basis(spot: f64, future: f64) -> PyResult { + Ok(ferro_ta_core::futures::basis::basis(spot, future)) +} + +#[pyfunction] +pub fn annualized_basis(spot: f64, future: f64, time_to_expiry: f64) -> PyResult { + Ok(ferro_ta_core::futures::basis::annualized_basis( + spot, + future, + time_to_expiry, + )) +} + +#[pyfunction] +pub fn implied_carry_rate(spot: f64, future: f64, time_to_expiry: f64) -> PyResult { + Ok(ferro_ta_core::futures::basis::implied_carry_rate( + spot, + future, + time_to_expiry, + )) +} + +#[pyfunction] +pub fn carry_spread(spot: f64, future: f64, rate: f64, time_to_expiry: f64) -> PyResult { + Ok(ferro_ta_core::futures::basis::carry_spread( + spot, + future, + rate, + time_to_expiry, + )) +} diff --git a/src/futures/curve.rs b/src/futures/curve.rs new file mode 100644 index 0000000..725a9b3 --- /dev/null +++ b/src/futures/curve.rs @@ -0,0 +1,52 @@ +use crate::validation; +use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1}; +use pyo3::prelude::*; + +#[pyfunction] +pub fn calendar_spreads<'py>( + py: Python<'py>, + futures_prices: PyReadonlyArray1<'py, f64>, +) -> PyResult>> { + Ok( + ferro_ta_core::futures::curve::calendar_spreads(futures_prices.as_slice()?) + .into_pyarray(py), + ) +} + +#[pyfunction] +pub fn curve_slope<'py>( + tenors: PyReadonlyArray1<'py, f64>, + futures_prices: PyReadonlyArray1<'py, f64>, +) -> PyResult { + let tenors = tenors.as_slice()?; + let futures_prices = futures_prices.as_slice()?; + validation::validate_equal_length(&[ + (tenors.len(), "tenors"), + (futures_prices.len(), "futures_prices"), + ])?; + Ok(ferro_ta_core::futures::curve::curve_slope( + tenors, + futures_prices, + )) +} + +#[pyfunction] +pub fn curve_summary<'py>( + spot: f64, + tenors: PyReadonlyArray1<'py, f64>, + futures_prices: PyReadonlyArray1<'py, f64>, +) -> PyResult<(f64, f64, f64, bool)> { + let tenors = tenors.as_slice()?; + let futures_prices = futures_prices.as_slice()?; + validation::validate_equal_length(&[ + (tenors.len(), "tenors"), + (futures_prices.len(), "futures_prices"), + ])?; + let summary = ferro_ta_core::futures::curve::curve_summary(spot, tenors, futures_prices); + Ok(( + summary.front_basis, + summary.average_basis, + summary.slope, + summary.is_contango, + )) +} diff --git a/src/futures/mod.rs b/src/futures/mod.rs new file mode 100644 index 0000000..b05b813 --- /dev/null +++ b/src/futures/mod.rs @@ -0,0 +1,38 @@ +//! PyO3 wrappers for futures analytics. + +mod basis; +mod curve; +mod roll; +mod synthetic; + +use pyo3::prelude::*; + +pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_function(pyo3::wrap_pyfunction!( + self::synthetic::synthetic_forward, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::synthetic::synthetic_spot, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::synthetic::parity_gap, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::basis::futures_basis, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::basis::annualized_basis, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::basis::implied_carry_rate, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::basis::carry_spread, m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::roll::weighted_continuous_contract, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::roll::back_adjusted_continuous_contract, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::roll::ratio_adjusted_continuous_contract, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::roll::roll_yield, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::curve::calendar_spreads, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::curve::curve_slope, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::curve::curve_summary, m)?)?; + Ok(()) +} diff --git a/src/futures/roll.rs b/src/futures/roll.rs new file mode 100644 index 0000000..03a9819 --- /dev/null +++ b/src/futures/roll.rs @@ -0,0 +1,75 @@ +use crate::validation; +use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1}; +use pyo3::prelude::*; + +#[pyfunction] +pub fn weighted_continuous_contract<'py>( + py: Python<'py>, + front: PyReadonlyArray1<'py, f64>, + next: PyReadonlyArray1<'py, f64>, + next_weights: PyReadonlyArray1<'py, f64>, +) -> PyResult>> { + let front = front.as_slice()?; + let next = next.as_slice()?; + let next_weights = next_weights.as_slice()?; + validation::validate_equal_length(&[ + (front.len(), "front"), + (next.len(), "next"), + (next_weights.len(), "next_weights"), + ])?; + Ok( + ferro_ta_core::futures::roll::weighted_continuous(front, next, next_weights) + .into_pyarray(py), + ) +} + +#[pyfunction] +pub fn back_adjusted_continuous_contract<'py>( + py: Python<'py>, + front: PyReadonlyArray1<'py, f64>, + next: PyReadonlyArray1<'py, f64>, + next_weights: PyReadonlyArray1<'py, f64>, +) -> PyResult>> { + let front = front.as_slice()?; + let next = next.as_slice()?; + let next_weights = next_weights.as_slice()?; + validation::validate_equal_length(&[ + (front.len(), "front"), + (next.len(), "next"), + (next_weights.len(), "next_weights"), + ])?; + Ok( + ferro_ta_core::futures::roll::back_adjusted_continuous(front, next, next_weights) + .into_pyarray(py), + ) +} + +#[pyfunction] +pub fn ratio_adjusted_continuous_contract<'py>( + py: Python<'py>, + front: PyReadonlyArray1<'py, f64>, + next: PyReadonlyArray1<'py, f64>, + next_weights: PyReadonlyArray1<'py, f64>, +) -> PyResult>> { + let front = front.as_slice()?; + let next = next.as_slice()?; + let next_weights = next_weights.as_slice()?; + validation::validate_equal_length(&[ + (front.len(), "front"), + (next.len(), "next"), + (next_weights.len(), "next_weights"), + ])?; + Ok( + ferro_ta_core::futures::roll::ratio_adjusted_continuous(front, next, next_weights) + .into_pyarray(py), + ) +} + +#[pyfunction] +pub fn roll_yield(front_price: f64, next_price: f64, time_to_expiry: f64) -> PyResult { + Ok(ferro_ta_core::futures::roll::roll_yield( + front_price, + next_price, + time_to_expiry, + )) +} diff --git a/src/futures/synthetic.rs b/src/futures/synthetic.rs new file mode 100644 index 0000000..67a7c35 --- /dev/null +++ b/src/futures/synthetic.rs @@ -0,0 +1,60 @@ +use pyo3::prelude::*; + +#[pyfunction] +pub fn synthetic_forward( + call_price: f64, + put_price: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, +) -> PyResult { + Ok(ferro_ta_core::futures::synthetic::synthetic_forward( + call_price, + put_price, + strike, + rate, + time_to_expiry, + )) +} + +#[pyfunction] +#[pyo3(signature = (call_price, put_price, strike, rate, time_to_expiry, carry = 0.0))] +pub fn synthetic_spot( + call_price: f64, + put_price: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + carry: f64, +) -> PyResult { + Ok(ferro_ta_core::futures::synthetic::synthetic_spot( + call_price, + put_price, + strike, + rate, + carry, + time_to_expiry, + )) +} + +#[pyfunction] +#[pyo3(signature = (call_price, put_price, spot, strike, rate, time_to_expiry, carry = 0.0))] +pub fn parity_gap( + call_price: f64, + put_price: f64, + spot: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + carry: f64, +) -> PyResult { + Ok(ferro_ta_core::futures::synthetic::parity_gap( + call_price, + put_price, + spot, + strike, + rate, + carry, + time_to_expiry, + )) +} diff --git a/src/lib.rs b/src/lib.rs index ed80206..f7bc361 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,8 +6,10 @@ pub mod chunked; pub mod crypto; pub mod cycle; pub mod extended; +pub mod futures; pub mod math_ops; pub mod momentum; +pub mod options; pub mod overlap; pub mod pattern; pub mod portfolio; @@ -57,6 +59,8 @@ fn _ferro_ta(m: &Bound<'_, PyModule>) -> PyResult<()> { streaming::register(m)?; extended::register(m)?; math_ops::register(m)?; + options::register(m)?; + futures::register(m)?; resampling::register(m)?; aggregation::register(m)?; portfolio::register(m)?; diff --git a/src/options/chain.rs b/src/options/chain.rs new file mode 100644 index 0000000..c2d055b --- /dev/null +++ b/src/options/chain.rs @@ -0,0 +1,64 @@ +use crate::validation; +use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1}; +use pyo3::prelude::*; + +#[pyfunction] +#[pyo3(signature = (strikes, reference_price, option_type = "call"))] +pub fn moneyness_labels<'py>( + py: Python<'py>, + strikes: PyReadonlyArray1<'py, f64>, + reference_price: f64, + option_type: &str, +) -> PyResult>> { + let kind = super::parse_option_kind(option_type)?; + let strikes = strikes.as_slice()?; + let labels = ferro_ta_core::options::chain::label_moneyness(strikes, reference_price, kind); + Ok(labels.into_pyarray(py)) +} + +#[pyfunction] +pub fn select_strike_offset<'py>( + strikes: PyReadonlyArray1<'py, f64>, + reference_price: f64, + offset: isize, +) -> PyResult> { + Ok(ferro_ta_core::options::chain::select_strike_by_offset( + strikes.as_slice()?, + reference_price, + offset, + )) +} + +#[pyfunction] +#[pyo3(signature = (strikes, vols, reference_price, time_to_expiry, target_delta, option_type = "call", model = "bsm", rate = 0.0, carry = 0.0))] +#[allow(clippy::too_many_arguments)] +pub fn select_strike_delta<'py>( + strikes: PyReadonlyArray1<'py, f64>, + vols: PyReadonlyArray1<'py, f64>, + reference_price: f64, + time_to_expiry: f64, + target_delta: f64, + option_type: &str, + model: &str, + rate: f64, + carry: f64, +) -> PyResult> { + let kind = super::parse_option_kind(option_type)?; + let model = super::parse_pricing_model(model)?; + let strikes = strikes.as_slice()?; + let vols = vols.as_slice()?; + validation::validate_equal_length(&[(strikes.len(), "strikes"), (vols.len(), "vols")])?; + Ok(ferro_ta_core::options::chain::select_strike_by_delta( + strikes, + vols, + ferro_ta_core::options::ChainGreeksContext { + model, + reference_price, + rate, + carry, + time_to_expiry, + kind, + }, + target_delta, + )) +} diff --git a/src/options/greeks.rs b/src/options/greeks.rs new file mode 100644 index 0000000..3b66bdf --- /dev/null +++ b/src/options/greeks.rs @@ -0,0 +1,125 @@ +use crate::validation; +use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1}; +use pyo3::prelude::*; + +type GreekArrays<'py> = ( + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, +); + +#[pyfunction] +#[pyo3(signature = (underlying, strike, rate, time_to_expiry, volatility, option_type = "call", model = "bsm", carry = 0.0))] +#[allow(clippy::too_many_arguments)] +pub fn option_greeks( + underlying: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + volatility: f64, + option_type: &str, + model: &str, + carry: f64, +) -> PyResult<(f64, f64, f64, f64, f64)> { + let kind = super::parse_option_kind(option_type)?; + let model = super::parse_pricing_model(model)?; + let greeks = + ferro_ta_core::options::greeks::model_greeks(ferro_ta_core::options::OptionEvaluation { + contract: ferro_ta_core::options::OptionContract { + model, + underlying, + strike, + rate, + carry, + time_to_expiry, + kind, + }, + volatility, + }); + Ok(( + greeks.delta, + greeks.gamma, + greeks.vega, + greeks.theta, + greeks.rho, + )) +} + +#[pyfunction] +#[pyo3(signature = (underlying, strike, rate, time_to_expiry, volatility, option_type = "call", model = "bsm", carry = None))] +#[allow(clippy::too_many_arguments)] +pub fn option_greeks_batch<'py>( + py: Python<'py>, + underlying: PyReadonlyArray1<'py, f64>, + strike: PyReadonlyArray1<'py, f64>, + rate: PyReadonlyArray1<'py, f64>, + time_to_expiry: PyReadonlyArray1<'py, f64>, + volatility: PyReadonlyArray1<'py, f64>, + option_type: &str, + model: &str, + carry: Option>, +) -> PyResult> { + let kind = super::parse_option_kind(option_type)?; + let model = super::parse_pricing_model(model)?; + let underlying = underlying.as_slice()?; + let strike = strike.as_slice()?; + let rate = rate.as_slice()?; + let time_to_expiry = time_to_expiry.as_slice()?; + let volatility = volatility.as_slice()?; + let carry_vec = match carry { + Some(array) => array.as_slice()?.to_vec(), + None => vec![0.0; underlying.len()], + }; + validation::validate_equal_length(&[ + (underlying.len(), "underlying"), + (strike.len(), "strike"), + (rate.len(), "rate"), + (time_to_expiry.len(), "time_to_expiry"), + (volatility.len(), "volatility"), + (carry_vec.len(), "carry"), + ])?; + + let mut delta = Vec::with_capacity(underlying.len()); + let mut gamma = Vec::with_capacity(underlying.len()); + let mut vega = Vec::with_capacity(underlying.len()); + let mut theta = Vec::with_capacity(underlying.len()); + let mut rho = Vec::with_capacity(underlying.len()); + for (((((&u, &k), &r), &t), &vol), &c) in underlying + .iter() + .zip(strike.iter()) + .zip(rate.iter()) + .zip(time_to_expiry.iter()) + .zip(volatility.iter()) + .zip(carry_vec.iter()) + { + let g = ferro_ta_core::options::greeks::model_greeks( + ferro_ta_core::options::OptionEvaluation { + contract: ferro_ta_core::options::OptionContract { + model, + underlying: u, + strike: k, + rate: r, + carry: c, + time_to_expiry: t, + kind, + }, + volatility: vol, + }, + ); + delta.push(g.delta); + gamma.push(g.gamma); + vega.push(g.vega); + theta.push(g.theta); + rho.push(g.rho); + } + + Ok(( + delta.into_pyarray(py), + gamma.into_pyarray(py), + vega.into_pyarray(py), + theta.into_pyarray(py), + rho.into_pyarray(py), + )) +} diff --git a/src/options/iv.rs b/src/options/iv.rs new file mode 100644 index 0000000..d5bba3d --- /dev/null +++ b/src/options/iv.rs @@ -0,0 +1,149 @@ +use crate::validation; +use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1}; +use pyo3::prelude::*; + +#[pyfunction] +#[pyo3(signature = (price, underlying, strike, rate, time_to_expiry, option_type = "call", model = "bsm", carry = 0.0, initial_guess = 0.2, tolerance = 1e-8, max_iterations = 100))] +#[allow(clippy::too_many_arguments)] +pub fn implied_volatility( + price: f64, + underlying: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + option_type: &str, + model: &str, + carry: f64, + initial_guess: f64, + tolerance: f64, + max_iterations: usize, +) -> PyResult { + let kind = super::parse_option_kind(option_type)?; + let model = super::parse_pricing_model(model)?; + Ok(ferro_ta_core::options::iv::implied_volatility( + ferro_ta_core::options::OptionContract { + model, + underlying, + strike, + rate, + carry, + time_to_expiry, + kind, + }, + price, + ferro_ta_core::options::IvSolverConfig { + initial_guess, + tolerance, + max_iterations, + }, + )) +} + +#[pyfunction] +#[pyo3(signature = (price, underlying, strike, rate, time_to_expiry, option_type = "call", model = "bsm", carry = None, initial_guess = None, tolerance = 1e-8, max_iterations = 100))] +#[allow(clippy::too_many_arguments)] +pub fn implied_volatility_batch<'py>( + py: Python<'py>, + price: PyReadonlyArray1<'py, f64>, + underlying: PyReadonlyArray1<'py, f64>, + strike: PyReadonlyArray1<'py, f64>, + rate: PyReadonlyArray1<'py, f64>, + time_to_expiry: PyReadonlyArray1<'py, f64>, + option_type: &str, + model: &str, + carry: Option>, + initial_guess: Option>, + tolerance: f64, + max_iterations: usize, +) -> PyResult>> { + let kind = super::parse_option_kind(option_type)?; + let model = super::parse_pricing_model(model)?; + let price = price.as_slice()?; + let underlying = underlying.as_slice()?; + let strike = strike.as_slice()?; + let rate = rate.as_slice()?; + let time_to_expiry = time_to_expiry.as_slice()?; + let carry_vec = match carry { + Some(array) => array.as_slice()?.to_vec(), + None => vec![0.0; price.len()], + }; + let guess_vec = match initial_guess { + Some(array) => array.as_slice()?.to_vec(), + None => vec![0.2; price.len()], + }; + validation::validate_equal_length(&[ + (price.len(), "price"), + (underlying.len(), "underlying"), + (strike.len(), "strike"), + (rate.len(), "rate"), + (time_to_expiry.len(), "time_to_expiry"), + (carry_vec.len(), "carry"), + (guess_vec.len(), "initial_guess"), + ])?; + + let out: Vec = price + .iter() + .zip(underlying.iter()) + .zip(strike.iter()) + .zip(rate.iter()) + .zip(time_to_expiry.iter()) + .zip(carry_vec.iter()) + .zip(guess_vec.iter()) + .map(|((((((&p, &u), &k), &r), &t), &c), &guess)| { + ferro_ta_core::options::iv::implied_volatility( + ferro_ta_core::options::OptionContract { + model, + underlying: u, + strike: k, + rate: r, + carry: c, + time_to_expiry: t, + kind, + }, + p, + ferro_ta_core::options::IvSolverConfig { + initial_guess: guess, + tolerance, + max_iterations, + }, + ) + }) + .collect(); + Ok(out.into_pyarray(py)) +} + +#[pyfunction] +#[pyo3(signature = (iv_series, window = 252))] +pub fn iv_rank<'py>( + py: Python<'py>, + iv_series: PyReadonlyArray1<'py, f64>, + window: i64, +) -> PyResult>> { + let window = validation::parse_timeperiod(window, "window", 1)?; + let out = ferro_ta_core::options::iv::iv_rank(iv_series.as_slice()?, window); + Ok(out.into_pyarray(py)) +} + +#[pyfunction] +#[pyo3(signature = (iv_series, window = 252))] +pub fn iv_percentile<'py>( + py: Python<'py>, + iv_series: PyReadonlyArray1<'py, f64>, + window: i64, +) -> PyResult>> { + let window = validation::parse_timeperiod(window, "window", 1)?; + let out = ferro_ta_core::options::iv::iv_percentile(iv_series.as_slice()?, window); + Ok(out.into_pyarray(py)) +} + +#[pyfunction] +#[pyo3(signature = (iv_series, window = 252))] +pub fn iv_zscore<'py>( + py: Python<'py>, + iv_series: PyReadonlyArray1<'py, f64>, + window: i64, +) -> PyResult>> { + let window = validation::parse_timeperiod(window, "window", 1)?; + let out = ferro_ta_core::options::iv::iv_zscore(iv_series.as_slice()?, window); + Ok(out.into_pyarray(py)) +} diff --git a/src/options/mod.rs b/src/options/mod.rs new file mode 100644 index 0000000..bd8fe52 --- /dev/null +++ b/src/options/mod.rs @@ -0,0 +1,67 @@ +//! PyO3 wrappers for options analytics. + +mod chain; +mod greeks; +mod iv; +mod pricing; +mod surface; + +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; + +pub(crate) fn parse_option_kind(option_type: &str) -> PyResult { + match option_type.to_ascii_lowercase().as_str() { + "call" | "c" => Ok(ferro_ta_core::options::OptionKind::Call), + "put" | "p" => Ok(ferro_ta_core::options::OptionKind::Put), + _ => Err(PyValueError::new_err(format!( + "option_type must be 'call' or 'put', got {option_type}" + ))), + } +} + +pub(crate) fn parse_pricing_model(model: &str) -> PyResult { + match model.to_ascii_lowercase().as_str() { + "bsm" | "black_scholes" | "black-scholes" | "blackscholes" => { + Ok(ferro_ta_core::options::PricingModel::BlackScholes) + } + "black76" | "black_76" | "black-76" => Ok(ferro_ta_core::options::PricingModel::Black76), + _ => Err(PyValueError::new_err(format!( + "model must be one of 'bsm'/'black_scholes' or 'black76', got {model}" + ))), + } +} + +pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_function(pyo3::wrap_pyfunction!(self::pricing::bsm_price, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::pricing::black76_price, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::pricing::bsm_price_batch, m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::pricing::black76_price_batch, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::greeks::option_greeks, m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::greeks::option_greeks_batch, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::iv::implied_volatility, m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::iv::implied_volatility_batch, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::iv::iv_rank, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::iv::iv_percentile, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::iv::iv_zscore, m)?)?; + m.add_function(pyo3::wrap_pyfunction!(self::surface::smile_metrics, m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::surface::term_structure_slope, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::chain::moneyness_labels, m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + self::chain::select_strike_offset, + m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(self::chain::select_strike_delta, m)?)?; + Ok(()) +} diff --git a/src/options/pricing.rs b/src/options/pricing.rs new file mode 100644 index 0000000..9ef5d83 --- /dev/null +++ b/src/options/pricing.rs @@ -0,0 +1,128 @@ +use crate::validation; +use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1}; +use pyo3::prelude::*; + +#[pyfunction] +#[pyo3(signature = (spot, strike, rate, time_to_expiry, volatility, option_type = "call", dividend_yield = 0.0))] +pub fn bsm_price( + spot: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + volatility: f64, + option_type: &str, + dividend_yield: f64, +) -> PyResult { + let kind = super::parse_option_kind(option_type)?; + Ok(ferro_ta_core::options::pricing::black_scholes_price( + spot, + strike, + rate, + dividend_yield, + time_to_expiry, + volatility, + kind, + )) +} + +#[pyfunction] +#[pyo3(signature = (forward, strike, rate, time_to_expiry, volatility, option_type = "call"))] +pub fn black76_price( + forward: f64, + strike: f64, + rate: f64, + time_to_expiry: f64, + volatility: f64, + option_type: &str, +) -> PyResult { + let kind = super::parse_option_kind(option_type)?; + Ok(ferro_ta_core::options::pricing::black_76_price( + forward, + strike, + rate, + time_to_expiry, + volatility, + kind, + )) +} + +#[pyfunction] +#[pyo3(signature = (spot, strike, rate, time_to_expiry, volatility, dividend_yield, option_type = "call"))] +#[allow(clippy::too_many_arguments)] +pub fn bsm_price_batch<'py>( + py: Python<'py>, + spot: PyReadonlyArray1<'py, f64>, + strike: PyReadonlyArray1<'py, f64>, + rate: PyReadonlyArray1<'py, f64>, + time_to_expiry: PyReadonlyArray1<'py, f64>, + volatility: PyReadonlyArray1<'py, f64>, + dividend_yield: PyReadonlyArray1<'py, f64>, + option_type: &str, +) -> PyResult>> { + let kind = super::parse_option_kind(option_type)?; + let spot = spot.as_slice()?; + let strike = strike.as_slice()?; + let rate = rate.as_slice()?; + let time_to_expiry = time_to_expiry.as_slice()?; + let volatility = volatility.as_slice()?; + let dividend_yield = dividend_yield.as_slice()?; + validation::validate_equal_length(&[ + (spot.len(), "spot"), + (strike.len(), "strike"), + (rate.len(), "rate"), + (time_to_expiry.len(), "time_to_expiry"), + (volatility.len(), "volatility"), + (dividend_yield.len(), "dividend_yield"), + ])?; + + let out: Vec = spot + .iter() + .zip(strike.iter()) + .zip(rate.iter()) + .zip(time_to_expiry.iter()) + .zip(volatility.iter()) + .zip(dividend_yield.iter()) + .map(|(((((&s, &k), &r), &t), &vol), &q)| { + ferro_ta_core::options::pricing::black_scholes_price(s, k, r, q, t, vol, kind) + }) + .collect(); + Ok(out.into_pyarray(py)) +} + +#[pyfunction] +#[pyo3(signature = (forward, strike, rate, time_to_expiry, volatility, option_type = "call"))] +pub fn black76_price_batch<'py>( + py: Python<'py>, + forward: PyReadonlyArray1<'py, f64>, + strike: PyReadonlyArray1<'py, f64>, + rate: PyReadonlyArray1<'py, f64>, + time_to_expiry: PyReadonlyArray1<'py, f64>, + volatility: PyReadonlyArray1<'py, f64>, + option_type: &str, +) -> PyResult>> { + let kind = super::parse_option_kind(option_type)?; + let forward = forward.as_slice()?; + let strike = strike.as_slice()?; + let rate = rate.as_slice()?; + let time_to_expiry = time_to_expiry.as_slice()?; + let volatility = volatility.as_slice()?; + validation::validate_equal_length(&[ + (forward.len(), "forward"), + (strike.len(), "strike"), + (rate.len(), "rate"), + (time_to_expiry.len(), "time_to_expiry"), + (volatility.len(), "volatility"), + ])?; + + let out: Vec = forward + .iter() + .zip(strike.iter()) + .zip(rate.iter()) + .zip(time_to_expiry.iter()) + .zip(volatility.iter()) + .map(|((((&f, &k), &r), &t), &vol)| { + ferro_ta_core::options::pricing::black_76_price(f, k, r, t, vol, kind) + }) + .collect(); + Ok(out.into_pyarray(py)) +} diff --git a/src/options/surface.rs b/src/options/surface.rs new file mode 100644 index 0000000..424d629 --- /dev/null +++ b/src/options/surface.rs @@ -0,0 +1,49 @@ +use crate::validation; +use numpy::PyReadonlyArray1; +use pyo3::prelude::*; + +#[pyfunction] +#[pyo3(signature = (strikes, vols, reference_price, time_to_expiry, model = "bsm", rate = 0.0, carry = 0.0))] +pub fn smile_metrics<'py>( + strikes: PyReadonlyArray1<'py, f64>, + vols: PyReadonlyArray1<'py, f64>, + reference_price: f64, + time_to_expiry: f64, + model: &str, + rate: f64, + carry: f64, +) -> PyResult<(f64, f64, f64, f64, f64)> { + let strikes = strikes.as_slice()?; + let vols = vols.as_slice()?; + validation::validate_equal_length(&[(strikes.len(), "strikes"), (vols.len(), "vols")])?; + let model = super::parse_pricing_model(model)?; + let metrics = ferro_ta_core::options::surface::smile_metrics( + strikes, + vols, + reference_price, + rate, + carry, + time_to_expiry, + model, + ); + Ok(( + metrics.atm_iv, + metrics.risk_reversal_25d, + metrics.butterfly_25d, + metrics.skew_slope, + metrics.convexity, + )) +} + +#[pyfunction] +pub fn term_structure_slope<'py>( + tenors: PyReadonlyArray1<'py, f64>, + atm_ivs: PyReadonlyArray1<'py, f64>, +) -> PyResult { + let tenors = tenors.as_slice()?; + let atm_ivs = atm_ivs.as_slice()?; + validation::validate_equal_length(&[(tenors.len(), "tenors"), (atm_ivs.len(), "atm_ivs")])?; + Ok(ferro_ta_core::options::surface::term_structure_slope( + tenors, atm_ivs, + )) +} diff --git a/src/statistic/beta.rs b/src/statistic/beta.rs index 39d3097..fc1c333 100644 --- a/src/statistic/beta.rs +++ b/src/statistic/beta.rs @@ -13,7 +13,7 @@ fn price_return(curr: f64, prev: f64) -> f64 { fn beta_fallback(x: &[f64], y: &[f64], timeperiod: usize) -> Vec { let n = x.len(); let mut result = vec![f64::NAN; n]; - for end in timeperiod..n { + for (end, slot) in result.iter_mut().enumerate().take(n).skip(timeperiod) { let start = end - timeperiod; let mut rx = vec![0.0_f64; timeperiod]; let mut ry = vec![0.0_f64; timeperiod]; @@ -36,7 +36,7 @@ fn beta_fallback(x: &[f64], y: &[f64], timeperiod: usize) -> Vec { .map(|&value| (value - mean_x).powi(2)) .sum::() / timeperiod as f64; - result[end] = if var_x != 0.0 { cov / var_x } else { f64::NAN }; + *slot = if var_x != 0.0 { cov / var_x } else { f64::NAN }; } result } @@ -102,8 +102,8 @@ pub fn beta<'py>( } } - for end in timeperiod..n { - result[end] = if invalid_pairs == 0 { + for (end, slot) in result.iter_mut().enumerate().take(n).skip(timeperiod) { + *slot = if invalid_pairs == 0 { let denom = period * sum_rx2 - sum_rx * sum_rx; if denom != 0.0 { (period * sum_rxry - sum_rx * sum_ry) / denom diff --git a/src/statistic/correl.rs b/src/statistic/correl.rs index 6131f2f..0070569 100644 --- a/src/statistic/correl.rs +++ b/src/statistic/correl.rs @@ -5,7 +5,7 @@ use pyo3::prelude::*; fn correl_fallback(x: &[f64], y: &[f64], timeperiod: usize) -> Vec { let n = x.len(); let mut result = vec![f64::NAN; n]; - for end in (timeperiod - 1)..n { + for (end, slot) in result.iter_mut().enumerate().take(n).skip(timeperiod - 1) { let wx = &x[(end + 1 - timeperiod)..=end]; let wy = &y[(end + 1 - timeperiod)..=end]; let mean_x = wx.iter().sum::() / timeperiod as f64; @@ -26,7 +26,7 @@ fn correl_fallback(x: &[f64], y: &[f64], timeperiod: usize) -> Vec { .sum::() .sqrt(); let denom = std_x * std_y; - result[end] = if denom != 0.0 { cov / denom } else { f64::NAN }; + *slot = if denom != 0.0 { cov / denom } else { f64::NAN }; } result } @@ -72,10 +72,10 @@ pub fn correl<'py>( .map(|(&lhs, &rhs)| lhs * rhs) .sum::(); - for end in (timeperiod - 1)..n { + for (end, slot) in result.iter_mut().enumerate().take(n).skip(timeperiod - 1) { let denom_x = period * sum_x2 - sum_x * sum_x; let denom_y = period * sum_y2 - sum_y * sum_y; - result[end] = if denom_x > 0.0 && denom_y > 0.0 { + *slot = if denom_x > 0.0 && denom_y > 0.0 { (period * sum_xy - sum_x * sum_y) / (denom_x * denom_y).sqrt() } else { f64::NAN diff --git a/tests/unit/test_data_pipeline.py b/tests/unit/test_data_pipeline.py index ec2876f..cbc8f7c 100644 --- a/tests/unit/test_data_pipeline.py +++ b/tests/unit/test_data_pipeline.py @@ -622,9 +622,15 @@ class TestComputeMany: close=close, ) - np.testing.assert_allclose(results[0], SMA(close, timeperiod=10), equal_nan=True) - np.testing.assert_allclose(results[1], EMA(close, timeperiod=12), equal_nan=True) - np.testing.assert_allclose(results[2], RSI(close, timeperiod=14), equal_nan=True) + np.testing.assert_allclose( + results[0], SMA(close, timeperiod=10), equal_nan=True + ) + np.testing.assert_allclose( + results[1], EMA(close, timeperiod=12), equal_nan=True + ) + np.testing.assert_allclose( + results[2], RSI(close, timeperiod=14), equal_nan=True + ) def test_hlc_indicators_match_public_api(self): from ferro_ta import ADX, ATR @@ -653,7 +659,9 @@ class TestComputeMany: from ferro_ta.data.batch import compute_many _, _, _, close, _ = _make_ohlcv(80) - result = compute_many([("STDDEV", {"timeperiod": 10, "nbdev": 2.0})], close=close) + result = compute_many( + [("STDDEV", {"timeperiod": 10, "nbdev": 2.0})], close=close + ) np.testing.assert_allclose( result[0], STDDEV(close, timeperiod=10, nbdev=2.0), equal_nan=True ) diff --git a/tests/unit/test_derivatives.py b/tests/unit/test_derivatives.py new file mode 100644 index 0000000..1d74e12 --- /dev/null +++ b/tests/unit/test_derivatives.py @@ -0,0 +1,218 @@ +import numpy as np +import pytest + + +class TestOptionsAnalytics: + def test_black_scholes_price_scalar(self): + from ferro_ta.analysis.options import black_scholes_price + + price = black_scholes_price( + 100.0, + 100.0, + 0.05, + 1.0, + 0.2, + option_type="call", + ) + assert price == pytest.approx(10.4506, rel=1e-4) + + def test_black_76_price_vectorized(self): + from ferro_ta.analysis.options import black_76_price + + price = black_76_price( + np.array([100.0, 105.0]), + np.array([100.0, 100.0]), + 0.03, + 1.0, + np.array([0.2, 0.25]), + option_type="call", + ) + assert isinstance(price, np.ndarray) + assert price.shape == (2,) + assert np.all(price > 0.0) + + def test_greeks_and_iv_recovery(self): + from ferro_ta.analysis.options import greeks, implied_volatility, option_price + + price = option_price( + 100.0, + 100.0, + 0.05, + 1.0, + 0.2, + option_type="call", + model="bsm", + ) + iv = implied_volatility( + price, + 100.0, + 100.0, + 0.05, + 1.0, + option_type="call", + model="bsm", + ) + result = greeks( + 100.0, + 100.0, + 0.05, + 1.0, + 0.2, + option_type="call", + model="bsm", + ) + assert iv == pytest.approx(0.2, rel=1e-6) + assert result.delta == pytest.approx(0.6368, rel=1e-3) + assert result.gamma > 0.0 + assert result.vega > 0.0 + + def test_smile_and_chain_helpers(self): + from ferro_ta.analysis.options import ( + label_moneyness, + select_strike, + smile_metrics, + term_structure_slope, + ) + + strikes = np.array([80.0, 90.0, 100.0, 110.0, 120.0]) + vols = np.array([0.30, 0.25, 0.20, 0.22, 0.27]) + + metrics = smile_metrics(strikes, vols, 100.0, 0.5) + labels = label_moneyness(strikes, 100.0, option_type="call") + + assert metrics.atm_iv == pytest.approx(0.20, rel=1e-6) + assert metrics.skew_slope < 0.0 + assert labels.tolist() == ["ITM", "ITM", "ATM", "OTM", "OTM"] + assert select_strike(strikes, 101.0, selector="ATM") == 100.0 + assert ( + select_strike(strikes, 101.0, option_type="call", selector="OTM2") == 120.0 + ) + assert select_strike( + strikes, + 100.0, + selector="DELTA0.25", + option_type="call", + volatilities=vols, + time_to_expiry=0.5, + ) in set(strikes.tolist()) + assert term_structure_slope([0.1, 0.5, 1.0], [0.18, 0.20, 0.22]) > 0.0 + + +class TestFuturesAnalytics: + def test_basis_and_curve_helpers(self): + from ferro_ta.analysis.futures import ( + annualized_basis, + basis, + calendar_spreads, + carry_spread, + curve_summary, + implied_carry_rate, + synthetic_forward, + ) + + assert basis(100.0, 103.0) == pytest.approx(3.0) + assert annualized_basis(100.0, 103.0, 0.25) > 0.0 + assert implied_carry_rate(100.0, 103.0, 0.25) > 0.0 + assert carry_spread(100.0, 103.0, 0.02, 0.25) > -1.0 + assert synthetic_forward(8.0, 5.0, 100.0, 0.02, 0.5) > 100.0 + assert np.allclose(calendar_spreads([100.0, 101.0, 103.0]), [1.0, 2.0]) + + summary = curve_summary(100.0, [0.1, 0.5, 1.0], [101.0, 102.0, 104.0]) + assert summary.is_contango is True + assert summary.slope > 0.0 + + def test_roll_helpers(self): + from ferro_ta.analysis.futures import ( + back_adjusted_continuous_contract, + ratio_adjusted_continuous_contract, + roll_yield, + weighted_continuous_contract, + ) + + front = np.array([100.0, 101.0, 102.0, 103.0]) + nxt = np.array([101.0, 102.0, 103.0, 104.0]) + weights = np.array([0.0, 0.25, 0.75, 1.0]) + + weighted = weighted_continuous_contract(front, nxt, weights) + back_adjusted = back_adjusted_continuous_contract(front, nxt, weights) + ratio_adjusted = ratio_adjusted_continuous_contract(front, nxt, weights) + + assert weighted.shape == front.shape + assert back_adjusted.shape == front.shape + assert ratio_adjusted.shape == front.shape + assert roll_yield(100.0, 102.0, 30.0 / 365.0) > 0.0 + + +class TestStrategyAndPayoff: + def test_strategy_schema_and_preset(self): + from ferro_ta.analysis.options_strategy import ( + DerivativesStrategy, + ExpirySelector, + ExpirySelectorKind, + LegPreset, + StrategyLeg, + StrikeSelector, + StrikeSelectorKind, + build_strategy_preset, + ) + + preset = build_strategy_preset( + LegPreset.STRADDLE, + name="ATM Straddle", + underlying="NIFTY", + expiry_selector=ExpirySelector(ExpirySelectorKind.CURRENT_WEEK), + ) + custom = DerivativesStrategy( + name="Custom Single", + legs=( + StrategyLeg( + "NIFTY", + ExpirySelector(ExpirySelectorKind.CURRENT_WEEK), + StrikeSelector( + StrikeSelectorKind.EXPLICIT, explicit_strike=22000.0 + ), + "call", + ), + ), + ) + + assert len(preset.legs) == 2 + assert custom.to_dict()["name"] == "Custom Single" + + def test_payoff_and_aggregate_greeks(self): + from ferro_ta.analysis.derivatives_payoff import ( + PayoffLeg, + aggregate_greeks, + strategy_payoff, + ) + + spot_grid = np.array([90.0, 100.0, 110.0]) + legs = [ + PayoffLeg( + instrument="option", + side="long", + option_type="call", + strike=100.0, + premium=5.0, + volatility=0.2, + time_to_expiry=0.5, + ), + PayoffLeg( + instrument="option", + side="short", + option_type="call", + strike=110.0, + premium=2.0, + volatility=0.22, + time_to_expiry=0.5, + ), + PayoffLeg(instrument="future", side="long", entry_price=100.0), + ] + + payoff = strategy_payoff(spot_grid, legs=legs) + greeks = aggregate_greeks(100.0, legs=legs) + + assert payoff.shape == spot_grid.shape + assert payoff[1] == pytest.approx(-3.0) + assert greeks.delta > 0.0 + assert greeks.gamma > 0.0