Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[run]
source = src/optpricing
omit =
src/optpricing/dashboard/pages/*
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ htmlcov/
site/

# Ignore my local notes file
todo.txt
todo/
notes/
text_drafts/
todo.txt
161 changes: 134 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# optpricing
# OptPricing: A Quantitative Finance Library for Derivative Pricing and Analysis

[![Tests](https://img.shields.io/github/actions/workflow/status/diljit22/quantfin/ci.yml?branch=main&label=tests)](https://github.com/diljit22/quantfin/actions/workflows/ci.yml)
[![Coverage](https://codecov.io/gh/diljit22/quantfin/branch/main/graph/badge.svg)](https://codecov.io/gh/diljit22/quantfin)
Expand All @@ -8,54 +8,161 @@
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**A Python library for pricing and calibrating financial options.**
`optpricing` is a Python library for pricing, calibrating, and analyzing financial derivatives. It is built with a focus on architectural clarity, model breadth, and practical usability through a robust API, command-line interface, and an interactive dashboard.

## Introduction
Diljit Singh
linkedin.com/in/singhdiljit/

Welcome to **optpricing**, a comprehensive Python toolkit for pricing and calibrating financial derivatives. This library was originally designed for me to learn about the more nuanced methods of quantitative finance and has since grown into a robust framework for analysis.
---

## Core Features

* **Model Library**: Implements a comprehensive set of models, including:
* **Stochastic Volatility**: Heston, SABR
* **Jump-Diffusion**: Merton, Bates, Kou, SABR with Jumps
* **Pure Levy Processes**: Variance Gamma (VG), Normal Inverse Gaussian (NIG), CGMY, Hyperbolic
* **Interest Rate Models**: Vasicek, Cox-Ingersoll-Ross (CIR), Put-Call Parity Implied Rate
* **Local Volatility**: Dupire's Equation

optpricing is structured around four core pillars:
* **Pricing Engines**: Provides a suite of numerical methods, allowing for technique comparison and validation:
* Analytic closed-form solutions
* Numerical integration and FFT-based pricing via characteristic functions
* Finite difference (PDE) solver using a Crank-Nicolson scheme
* Binomial and trinomial tree methods (CRR, TOPM, Leisen-Reimer) for European and American options
* High-performance Monte Carlo engine for European and American options, accelerated with `numba`, featuring variance reduction techniques (e.g., antithetic variates, control variates, importance sampling)

- **Atoms**: Fundamental data types (`Option`, `Stock`, `Rate`) that ensure consistency and clarity of inputs across the library.
- **Models**: A broad library ranging from classical Black-Scholes-Merton to advanced stochastic volatility (Heston, SABR) and jump/Levy processes.
- **Techniques**: Multiple pricing engines—closed-form formulas, FFT, numerical integration, PDE solvers, lattice methods, and Monte Carlo (`numba`-accelerated with variance reduction methods baked in).
- **Workflows**: High-level orchestrators that automate end-to-end tasks like daily calibration and out-of-sample backtesting, all accessible via a CLI or an interactive dashboard.
* **Interfaces**:
* **Programmatic API**: Use the package as a Python library to build custom financial models in your scripts. Define options, stocks, rates, and models programmatically to compute prices and other metrics.
* **Command-Line Interface (CLI)**: A robust CLI for live pricing, data management, model calibration, and historical backtesting.
* **Interactive Dashboard (UI)**: A Streamlit application for visual analysis of option chains, implied volatility surfaces, and model calibrations.

* **Workflow Automation**: High-level classes that orchestrate complex tasks like daily calibration runs and out-of-sample performance evaluation.

---

## Quick Start

Get started in minutes using the command-line interface.
`optpricing` is designed for a straightforward installation using `pip` and is compatible with Python 3.10 and higher.

### 1. Install the Library

```bash
# 1. Install the library with all features, including the dashboard
pip install "optpricing"
pip install optpricing
```

# 2. Download historical data for a ticker (used by some models)
### 2. Download Historical Data

Some models require historical data (e.g., for calibration). Download data for a ticker like SPY:

```bash
optpricing data download --ticker SPY
```

For more details, see the [Getting Started Guide]((guide/getting_started.md)).

### 3. Use the CLI

Price an option directly from the terminal. The command below fetches the live option chain for AAPL, retrieves the current dividend rate, calculates the implied risk-free rate from at-the-money contracts, and prices the contract with Heston’s model using its default pricing technique (FFT):

```bash
optpricing price --ticker AAPL --strike 630 --maturity 2025-12-19 --model Heston --param "rho=-0.7" --param "vol_of_vol=0.5"
```

To price the same contract as an American Option use:

```bash
optpricing price -t AAPL -k 210 -T 2025-12-19 --style american --model Heston --param "rho=-0.7" --param "vol_of_vol=0.5"
```

For more details, see the [CLI Guide]((guide/CLI.md)).

### 4. Launch the Dashboard

# 3. Launch the interactive dashboard to visualize the results
Visualize option chains and model outputs, interact with a pricing calculator featuring 15 models and 10 techniques.

```bash
optpricing dashboard
```

For more details, see the [Dashboard Guide]((guide/dashboard.md)).

### 5. Use the Programmatic API

The most powerful way to use the package is via the API, which provides customization of nearly every aspect of pricing:

```python
from optpricing import Option, OptionType, Rate, Stock, ZeroCouponBond
from optpricing.models import BSMModel, CIRModel, VasicekModel
from optpricing.techniques import ClosedFormTechnique

# Define an option, underlying and rate
option = Option(strike=105, maturity=1.0, option_type=OptionType.CALL)
stock = Stock(spot=100, dividend=0.01)
rate = Rate(rate=0.05)

# Choose a model and technique
bsm_model = BSMModel(params={"sigma": 0.20})
cf_technique = ClosedFormTechnique()

result = cf_technique.price(option, stock, bsm_model, rate)
print(f"The option price is: {result.price:.4f}")


delta = cf_technique.delta(option, stock, bsm_model, rate)
gamma = cf_technique.gamma(option, stock, bsm_model, rate)
vega = cf_technique.vega(option, stock, bsm_model, rate)

print(f"Delta: {delta:.4f}")
print(f"Gamma: {gamma:.4f}")
print(f"Vega: {vega:.4f}")

target_price = 7.50
iv = cf_technique.implied_volatility(
option, stock, bsm_model, rate, target_price=target_price
)
print(f"Implied volatility for price ${target_price:.2f}: {iv:.4%}")


# Zero Coupon Bond
bond = ZeroCouponBond(maturity=1.0)
r0_stock = Stock(spot=0.05) # initial short rate
dummy_rate = Rate(rate=0.0) # ignored by rate models

vasicek = VasicekModel(params={"kappa": 0.86, "theta": 0.09, "sigma": 0.02})
cir = CIRModel(params={"kappa": 0.86, "theta": 0.09, "sigma": 0.02})

p_vasi = cf_technique.price(bond, r0_stock, vasicek, dummy_rate).price
p_cir = cf_technique.price(bond, r0_stock, cir, dummy_rate).price

print(f"Vasicek ZCB Price: {p_vasi:.4f}")
print(f"CIR ZCB Price: {p_cir:.4f}")
```

## Documentation & Links
For more details, see the [API Guide]((guide/API.md)).

---

## Documentation

The full documentation includes installation instructions, user guides, examples, and a complete API reference.

For a detailed tutorial, full API reference, and more examples, please see the official documentation.
* **[View the Official Documentation](https://diljit22.github.io/quantfin/)**

- **Getting Started**:
[Installation Guide](https://diljit22.github.io/quantfin/guide/installation/) ·
[Walkthrough](https://diljit22.github.io/quantfin/guide/getting_started/)
### Guides

- **Documentation**:
[API Reference](https://diljit22.github.io/quantfin)
* [Introduction](guide/introduction.md)
* [Installation](guide/installation.md)
* [Getting Started](guide/getting_started.md)
* [CLI](guide/CLI.md)
* [Dashboard](guide/dashboard.md)
* [API](guide/API.md)
* [Examples](guide/examples.md)
* [API Reference](reference/index.md)

- **Interactive Dashboard**:
[Launch the UI](https://diljit22.github.io/quantfin/guide/dashboard/)
## Contributing

- **About Me**:
[LinkedIn](https://www.linkedin.com/in/singhdiljit/)
Contributions are welcome; see [CONTRIBUTING](/CONTRIBUTING.md) for details.

## Contributing & License
## License

See [CONTRIBUTING](/CONTRIBUTING.md) and [LICENSE](LICENSE).
This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
2 changes: 2 additions & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ coverage:
status:
project:
enabled: false
ignore:
- "src/optpricing/dashboard/pages/*"
127 changes: 127 additions & 0 deletions docs/guide/API.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Guide: Programmatic API

The `optpricing` Python API provides a powerful, object-oriented framework for building custom financial analysis scripts and workflows. Its modular design allows you to mix and match models, techniques, and data to suit your specific research needs.

This guide covers the fundamental components and provides examples for common use cases.

---

## Core Concepts: Atoms, Models, and Techniques

All programmatic workflows are built on three core components:

1. **Atoms**: Immutable data classes like `Option`, `Stock`, and `Rate` that represent the basic inputs.
2. **Models**: Classes representing financial theories, such as `BSMModel` or `HestonModel` (and many others).
3. **Techniques**: Classes representing numerical algorithms, such as `ClosedFormTechnique` or `MonteCarloTechnique` (and many others).

You instantiate these components and pass them to a technique's `price` method to get a result.

## Example 1: Pricing a Standard European Option

This example demonstrates the most common use case: pricing a European call option using the Black-Scholes-Merton model's analytic formula.

```python
from optpricing import Option, OptionType, Rate, Stock
from optpricing.models import BSMModel
from optpricing.techniques import ClosedFormTechnique

# 1. Define the core Atoms
option = Option(strike=105, maturity=1.0, option_type=OptionType.CALL)
stock = Stock(spot=100.0, dividend=0.01)
rate = Rate(rate=0.05)

# 2. Instantiate the Model and Technique
bsm_model = BSMModel(params={"sigma": 0.20})
cf_technique = ClosedFormTechnique()

# 3. Calculate the price and Greeks
result = cf_technique.price(option, stock, bsm_model, rate)
delta = cf_technique.delta(option, stock, bsm_model, rate)
gamma = cf_technique.gamma(option, stock, bsm_model, rate)

print(f"The option price is: {result.price:.4f}")
print(f"Delta: {delta:.4f}")
print(f"Gamma: {gamma:.4f}")
```

## Example 2: Pricing an American Option with Monte Carlo

The API's flexibility allows you to easily switch to more complex scenarios. Here, we price an American option using the Heston model with the Longstaff-Schwartz Monte Carlo method.

```python
from optpricing.models import HestonModel
from optpricing.techniques import AmericanMonteCarloTechnique

# 1. Define an American option Atom
american_option = Option(strike=105, maturity=1.0, option_type=OptionType.PUT)

# 2. Instantiate a more complex model and the appropriate technique
heston_model = HestonModel(params={
"v0": 0.04,
"kappa": 2.0,
"theta": 0.05,
"rho": -0.7,
"vol_of_vol": 0.5
})
lsmc_technique = AmericanMonteCarloTechnique(n_paths=20000, n_steps=100)

# 3. Calculate the price
# Note: The 'v0' parameter is passed as a keyword argument for the simulation
result = lsmc_technique.price(
american_option,
stock,
heston_model,
rate,
v0=heston_model.params['v0']
)
print(f"The American option price is: {result.price:.4f}")
```

## Example 3: Calculating Implied Volatility

The library includes mixins for common tasks like calculating implied volatility. This functionality is available on most technique objects.

```python
# Using the components from Example 1
target_price = 7.50

iv = cf_technique.implied_volatility(
option,
stock,
bsm_model,
rate,
target_price=target_price
)

print(f"Implied volatility for a target price of ${target_price:.2f}: {iv:.4%}")
```

## Example 4: Pricing an Interest Rate Product

The framework is not limited to equity options. It can be used to price other derivatives, such as Zero-Coupon Bonds using short-rate models.

```python
from optpricing.atoms import ZeroCouponBond
from optpricing.models import VasicekModel

# 1. Define a ZeroCouponBond Atom
bond = ZeroCouponBond(maturity=5.0, face_value=1000.0)

# 2. For rate models, the 'stock.spot' is re-interpreted as the initial short rate r0
r0_stock = Stock(spot=0.03)
# The 'rate' atom is ignored by rate models but required by the technique signature
dummy_rate = Rate(rate=0.0)

# 3. Instantiate the Vasicek model
vasicek_model = VasicekModel(params={"kappa": 0.86, "theta": 0.05, "sigma": 0.02})

# 4. Price using the ClosedFormTechnique
price_result = cf_technique.price(bond, r0_stock, vasicek_model, dummy_rate)
print(f"Price of 5-Year ZCB under Vasicek model: ${price_result.price:.2f}")
```

## Advanced Usage: Extending the Library

The library's true power lies in its extensibility. By inheriting from `BaseModel` and `BaseTechnique`, you can easily add your own custom models and pricing algorithms, which will automatically integrate with the existing framework.

For a complete and detailed list of all available classes, methods, and functions, please consult the full **[API Reference](../reference/index.md)**.
Loading