← Back to documentation

API Reference

Core Python APIs and dataclasses in floe.

Pricing (blackscholes)

black_scholes

from floe import BlackScholesParams, black_scholes

price = black_scholes(
    BlackScholesParams(
        spot=100,
        strike=105,
        time_to_expiry=0.25,
        risk_free_rate=0.05,
        volatility=0.20,
        option_type="call",
    )
)

black_scholes computes the European Black–Scholes–Merton price per unit at full IEEE-754 float precision without Greeks or cent rounding. At zero time to expiration it returns the intrinsic value, and at zero volatility the discounted deterministic payoff max(0, ±(S·e^(−qT) − K·e^(−rT))). Zero spot is valid (K·e^(−rT) for a put). Negative spot, time, or volatility, a non-positive strike, non-finite numbers, or unknown option types raise ValueError. calculate_greeks().price continues to round to two decimals.

calculate_greeks

from floe import calculate_greeks

g = calculate_greeks(params)
print(g.price, g.delta, g.gamma, g.theta, g.vega, g.rho)
print(g.vanna, g.charm, g.volga, g.speed, g.zomma, g.color, g.ultima)

calculate_implied_volatility

from floe import calculate_implied_volatility

iv_percent = calculate_implied_volatility(
    3.50,   # option price
    100.0,  # spot
    105.0,  # strike
    0.05,   # risk-free rate
    0.01,   # dividend yield
    0.25,   # time to expiry (years)
    "call",
)

The bisection solver inverts the unrounded full-precision price rather than a cent-rounded price. Non-positive or non-finite inputs continue to return 0.0 instead of raising ValueError.

get_time_to_expiration_in_years

from floe import get_time_to_expiration_in_years

tte = get_time_to_expiration_in_years(expiration_ms, now_ms)

Statistics (statistics)

from floe import cumulative_normal_distribution, normal_pdf

cdf = cumulative_normal_distribution(1.96)
pdf = normal_pdf(0)

Volatility Surfaces (volatility)

get_iv_surfaces

from floe import get_iv_surfaces

surfaces = get_iv_surfaces("totalvariance", chain, now_ms)

get_iv_for_strike

from floe import get_iv_for_strike

iv_at_k = get_iv_for_strike(surfaces, expiry_ms, "call", 450)

smooth_total_variance_smile

from floe import smooth_total_variance_smile

smoothed = smooth_total_variance_smile(
    [440, 445, 450, 455, 460],
    [23, 21, 19, 20, 22],
    0.08,
)

Dealer Exposure (exposure)

calculate_gamma_vanna_charm_exposures

from floe import ExposureCalculationOptions, calculate_gamma_vanna_charm_exposures

variants = calculate_gamma_vanna_charm_exposures(
    chain,
    surfaces,
    ExposureCalculationOptions(as_of_timestamp=now_ms),
)

for v in variants:
    print(v.expiration, v.canonical.total_net_exposure)

calculate_shares_needed_to_cover

from floe import calculate_shares_needed_to_cover

cover = calculate_shares_needed_to_cover(900_000_000, total_net_exposure, spot)
print(cover.action_to_cover, cover.shares_to_cover, cover.implied_move_to_cover)

Hedge Flow (hedgeflow)

compute_hedge_impulse_curve

from floe import HedgeImpulseConfig, compute_hedge_impulse_curve

curve = compute_hedge_impulse_curve(
    canonical_exposure,
    call_surface,
    HedgeImpulseConfig(range_percent=3, step_percent=0.05, kernel_width_strikes=2),
    now_ms,
)

compute_charm_integral

from floe import CharmIntegralConfig, compute_charm_integral

charm = compute_charm_integral(
    canonical_exposure,
    CharmIntegralConfig(time_step_minutes=15),
    now_ms,
)

analyze_hedge_flow

from floe import analyze_hedge_flow, HedgeImpulseConfig, CharmIntegralConfig

analysis = analyze_hedge_flow(
    canonical_exposure,
    call_surface,
    HedgeImpulseConfig(),
    CharmIntegralConfig(),
    now_ms,
)

Implied Probability (impliedpdf)

estimate_implied_probability_distribution

from floe import estimate_implied_probability_distribution

result = estimate_implied_probability_distribution(
    "QQQ",
    502.5,
    call_options,
    now_ms,
)

estimate_implied_probability_distributions

from floe import estimate_implied_probability_distributions

dists = estimate_implied_probability_distributions(
    "QQQ",
    502.5,
    all_options,
    now_ms,
)

Query helpers

from floe import get_probability_in_range, get_cumulative_probability, get_quantile

prob = get_probability_in_range(dist, 495, 510)
cum = get_cumulative_probability(dist, 500)
q90 = get_quantile(dist, 0.90)

Exposure-adjusted PDF

from floe import DEFAULT_ADJUSTMENT_CONFIG, estimate_exposure_adjusted_pdf

adjusted = estimate_exposure_adjusted_pdf(
    "QQQ",
    502.5,
    call_options,
    exposure_snapshot,
    DEFAULT_ADJUSTMENT_CONFIG,
    now_ms,
)

IV vs RV (iv, rv, volresponse)

Model-free IV

from floe import compute_model_free_iv

near = compute_model_free_iv(near_term_options, spot, 0.05, now_ms)
interp = compute_model_free_iv(near_term_options, spot, 0.05, now_ms, far_term_options, 30)

Realized volatility

from floe import compute_realized_volatility

rv_result = compute_realized_volatility(observations)

Vol response z-score

from floe import build_vol_response_observation, compute_vol_response_z_score

obs = build_vol_response_observation(current_iv, current_rv, current_spot, now_ms, prev_iv, prev_spot)
result = compute_vol_response_z_score(series)

OCC / Adapters / API Client

from floe import build_occ_symbol, parse_occ_symbol, create_option_chain, ApiClient

Profit and Loss (pnl)

All P&L functions and dataclasses are synchronous, zero-dependency, and re-exported directly from floe (as well as floe.pnl). Packed numeric buffers use Python's standard array('d'), supporting zero-copy memoryview slicing and optional downstream numpy.frombuffer(batch.pnl, dtype=np.float64) integration without making NumPy a dependency.

Entry point Result
calculate_pnl(position, market, scenario=None) Single-spot valuation, signed position value, P&L, total entry cost, and scenario metadata
calculate_pnl_curve(position, market, options=None) Curve points, analytic or numerical break-evens, expiration bounds, and sampled extrema
calculate_pnl_curves(items, defaults=None) Packed array('d') P&L buffer, interned shared grids, and per-position metadata
calculate_pnl_surface(position, market, options) Two axis vectors, width, height, row-major array('d') P&L buffer, and grid min/max
prepare_pnl_position(position, market) Reusable snapshot with calculate_point, calculate_curve, calculate_surface, calculate_envelope, and resolve_smile

Positions and Market Context

Each PnLPosition has one underlying, a non-empty legs sequence (PnLOptionLeg or PnLStockLeg), optional id, symbol, and non-negative fees. Positive quantities are long and negative quantities are short.

import time
from floe import (
    PnLCurveOptions,
    PnLMarketContext,
    PnLOptionLeg,
    PnLPointOptions,
    PnLPosition,
    PnLStockLeg,
    calculate_pnl,
    prepare_pnl_position,
)

now = int(time.time() * 1000)
expiration_timestamp = now + 7 * 86_400_000
market = PnLMarketContext(as_of_timestamp=now, spot=354.0, risk_free_rate=0.04)

position = PnLPosition(
    symbol="AAPL",
    fees=1.50,
    legs=[
        PnLStockLeg(quantity=100, entry_price=350.0),
        PnLOptionLeg(
            option_type="call",
            strike=360.0,
            quantity=-1,
            entry_price=3.0,
            implied_volatility=0.25,
            expiration_timestamp=expiration_timestamp,
        ),
    ],
)

point = calculate_pnl(position, market, PnLPointOptions(spot=355.0, include_leg_breakdown=True))
prepared = prepare_pnl_position(position, market)
reference = prepared.calculate_curve(PnLCurveOptions(evaluation_timestamp=expiration_timestamp))
next_day = prepared.calculate_curve(
    PnLCurveOptions(evaluation_timestamp=now + 86_400_000, volatility_shift=0.05)
)

Curves, Break-Evens, and Bounds

price_range=PnLPriceRange(min, max, points) defines a uniform base grid (defaulting to 500 points widened by exp(±2σ√T) clamped between 5% and 75%, or ±20% when no IV is known). Alternatively pass a strictly increasing spots sequence.

  • Analytic expiration payoff: When all option legs share one expiration and evaluation_timestamp equals that expiration (or the position is stock-only), break_evens (method="analytic", complete=True) and expiration_statistics (max_profit, max_loss, max_profit_regions, max_loss_regions) are exact across [0, +∞).
  • Numerical break-evens: Pre-expiration and front-expiration calendar curves refine sign crossings via bisection and local extrema via ternary search (method="numerical", complete=False). Customize via root_search=PnLRootSearch(...).

Volatility Scenarios

All P&L implied volatilities and shifts are annualized decimals (0.05 adds five percentage points). Legacy IVSurface values in percent are converted once during preparation.

PnLVolatilityModel.kind Assumption
"constant" (default) Hold each leg's baseline IV constant (or interpolate the reference surface if leg IV is None).
"stickyStrike" Read the reference smile at the fixed contract strike and original tenor.
"stickyMoneyness" Read the original tenor at strike * reference_spot / scenario_spot.
"coupled" Apply directional (beta_return) and absolute (beta_abs_return) log-return stresses to baseline IV.
"dynamic" Roll the smile along spot moneyness and remaining tenor, plus skew, curvature, and annual_drift stresses.

Pass any Python callable (PnLVolatilityContext) -> float as volatility_resolver for custom volatility models:

from floe import PnLPointOptions, PnLScenario, PnLVolatilityModel

custom = prepared.calculate_point(
    PnLPointOptions(
        volatility_resolver=lambda ctx: (ctx.base_iv or 0.25)
        + (0.04 if ctx.scenario_spot < ctx.reference_spot else 0.0),
        volatility_shift=0.01,
    )
)
smile = prepared.resolve_smile(
    1,
    [340, 350, 360, 370],
    PnLScenario(spot=345, volatility_model=PnLVolatilityModel(kind="dynamic", beta_return=-0.25, curvature=0.2)),
)

Batch Curves and Zero-Copy Buffers

calculate_pnl_curves(items, defaults=None) packs every row's P&L into a contiguous array('d') buffer and interns identical grids:

from floe import PnLBatchFailure, PnLBatchItem, PnLBatchOptions, PnLPriceRange, calculate_pnl_curves

batch = calculate_pnl_curves(
    [PnLBatchItem(prepared=prepared), PnLBatchItem(position=position, market=market)],
    PnLBatchOptions(
        on_error="collect",
        price_range=PnLPriceRange(min=300, max=400, points=50),
        include_statistics=False,
    ),
)

view = memoryview(batch.pnl)  # zero-copy PEP 3118 buffer view
for row in batch.rows:
    if isinstance(row, PnLBatchFailure):
        continue
    prices = batch.grids[row.grid_index]
    row_pnl = view[row.offset : row.offset + row.length]

Benchmarks

Run PYTHONPATH=src python benchmarks/pnl.py for standard-library perf_counter, timeit, and tracemalloc measurements. Medians on an Apple M3 Max (CPython 3.14, pure Python, zero dependencies):

Workload Median Peak Alloc
100 expiration curves × 50 points (1 leg) 1.6 ms 135 KB
100 expiration curves × 500 points (1 leg) 10.3 ms 496 KB
1 theoretical curve × 501 points, roots + stats 0.99 ms 122 KB
100 theoretical curves × 500 points (1 leg / 4 legs) 46 ms / 171 ms 497 KB / 502 KB
100 four-leg curves × 500 points, coupled IV 244 ms 509 KB
1 spot/time surface, 200 × 100 18.0 ms 164 KB
10,000 prices: black_scholes / calculate_greeks 16.6 ms / 28.7 ms —