Skip to content

Repository files navigation

diffuse

Quantitative Finance Engine — Heat Equation PDE Option Pricing & Prediction Market Analysis

Diffuse prices European, American, and barrier options by solving the Black-Scholes PDE via a transformation to the heat equation. It then applies finite-difference numerical schemes (Crank-Nicolson, FTCS, BTCS) to compute prices, full Greeks, and 3D price surfaces. Includes a trader-style web UI, REST API, WebSocket streaming, CLI, and Docker deployment.

Extends to prediction markets: Fits drift-diffusion models to probability time series from Manifold Markets and Polymarket to detect mispricing and arbitrage opportunities.

Features

Domain Feature
Option Pricing European calls/puts, American puts (early exercise), Barrier (knock-out) options
Numerical Methods Crank-Nicolson (2nd-order, default), BTCS (implicit), FTCS (explicit)
Risk Analytics Full Greeks — Delta, Gamma, Theta, Vega, Rho via finite differences
Visualization 3D Interactive price surface (strike × maturity), trade history chart
Live Trading UI React + Tailwind terminal-style dashboard with WebSocket streaming
Prediction Markets Manifold Markets & Polymarket API clients with diffusion arbitrage scanning
API FastAPI REST with RS256 JWT auth, auto-generated Swagger docs
CLI Click-based command-line interface for batch pricing and market analysis
Deployment Docker Compose (nginx + API + Postgres + Redis)

Quick Start — Web UI

# 1. Start the API server
uvicorn diffuse.api.main:app --host 127.0.0.1 --port 8000

# 2. Start the frontend (separate terminal)
cd frontend && npm install && npm run dev

Open http://localhost:5173, enter your JWT Bearer token, set parameters, and click PRICE.


Quick Start — CLI

# Install the package
pip install -e .

# Price a European call
diffuse price --S0 100 --K 100 --sigma 0.2 --T 1.0

# Get Greeks as JSON
diffuse greeks --S0 100 --K 100 --sigma 0.2 --T 1.0 --json

Quick Start — Python

from diffuse.finance.greeks import compute_all_greeks

greeks = compute_all_greeks(S0=100, K=100, r=0.05, q=0.0, sigma=0.2, T=1.0)

for name, value in greeks.items():
    print(f"{name:>6s}: {value:.10f}")
# Output:
#  delta: 0.6368306512
#  gamma: 0.0187618023
#  theta: -1.0907789103
#   vega: 0.3752360448
#    rho: 0.5325399913

Docker Deployment

# Full stack (API + nginx + Postgres + Redis)
docker compose -f docker/docker-compose.yml up --build

The app will be available at http://localhost. The nginx reverse proxy handles:

  • Static frontend files
  • API requests via /api/*
  • WebSocket connections via /ws/*

Frontend Deployment (Vercel)

See deploy_app_into.md for step-by-step Vercel deployment instructions.

Quick summary:

Setting Value
Framework Vite
Root directory frontend
Build command npm run build
Output directory dist
Install command npm install

REST API

Start the server:

uvicorn diffuse.api.main:app --host 0.0.0.0 --port 8000

Endpoints

Method Path Auth Description
POST /price JWT Price an option — returns price + Greeks
POST /greeks JWT Compute Greeks only
POST /surface JWT Compute price surface (strike × maturity grid)
GET /health Health check
GET /metrics Prometheus metrics
WS /ws/price?token=<jwt> JWT WebSocket live pricing stream

Swagger docs at http://localhost:8000/docs.

Example — POST /price

// Request
{
  "option_type": "european_call",
  "S0": 100, "K": 100, "sigma": 0.2, "T": 1.0,
  "r": 0.05, "q": 0.0, "scheme": "cn",
  "N_x": 500, "N_t": 500
}

// Response
{
  "price": 10.4505835722,
  "greeks": {
    "delta": 0.6368306512,
    "gamma": 0.0187618023,
    "theta": -1.0907789103,
    "vega": 0.3752360448,
    "rho": 0.5325399913
  },
  "scheme_used": "cn",
  "courant_number": 0.499002,
  "request_id": "abc123..."
}

CLI Reference

# Price an option
diffuse price --S0 100 --K 100 --sigma 0.2 --T 1.0

# With all options
diffuse price --S0 100 --K 100 --sigma 0.3 --T 1.0 \
  --type american_put --scheme cn --N-x 501 --N-t 501 --json

# Compute Greeks
diffuse greeks --S0 100 --K 100 --sigma 0.2 --T 1.0 --json

# Start API server
diffuse serve --host 0.0.0.0 --port 8000 --reload

Configuration

Set via environment variables or .env file:

Variable Default Description
DATABASE_URL sqlite+aiosqlite:///./diffuse.db Database URL
REDIS_URL redis://localhost:6379/0 Redis URL
JWT_PUBLIC_KEY_PEM (required) RS256 public key
JWT_PRIVATE_KEY_PEM (required) RS256 private key
ALLOWED_ORIGINS ["http://localhost:3000"] CORS origins
LOG_LEVEL INFO Logging level

Generate keys:

bash scripts/generate_keys.sh

Development

pip install -r requirements-dev.txt
pytest tests/ -v --cov=src/diffuse --cov-report=term-missing
ruff check src/
mypy src/

Architecture

src/diffuse/
├── solver/          # PDE: grid, FTCS/BTCS/CN schemes, solver
├── finance/         # Black-Scholes transform, payoffs, Greeks
├── markets/         # Manifold Markets & Polymarket API clients
│   ├── manifold.py  #   → api.manifold.markets/v0
│   ├── polymarket.py #  → clob.polymarket.com
│   └── arb.py       #   → cross-platform arbitrage scanner
├── api/             # FastAPI (routes, auth, audit, WebSocket)
├── cli/             # Click CLI
└── config.py        # Environment config

frontend/
├── src/
│   ├── App.tsx                # Main app with QF branding
│   ├── components/            # UI components
│   │   ├── ApiKeyInput.tsx
│   │   ├── HowItWorks.tsx      # Algorithm explainer
│   │   ├── ParamsForm.tsx
│   │   ├── PriceDisplay.tsx
│   │   ├── TradeChart.tsx
│   │   ├── GreeksPanel.tsx
│   │   └── SurfacePlot3D.tsx
│   ├── hooks/
│   │   └── useWebSocket.ts    # WS with auto-reconnect
│   └── types.ts
└── ...                        # Vite + Tailwind config

Pricing Pipeline

BS params → heat transform → initial condition → PDE solve → inverse transform → price + Greeks

Prediction Market Pipeline

Market API → probability series → log-odds transform → diffusion model fit → mispricing detection

License

Proprietary. All rights reserved.

Releases

Packages

Contributors

Languages