A professional Black-Scholes option pricing application with interactive P&L analysis and advanced visualization capabilities.
Website: πΏ Sigma Option babyyyyyyy!
The application is currently available for local deployment. Web hosting coming soon!
Sigma Option is a full-stack quantitative finance application implementing the Black-Scholes-Merton model with an emphasis on practical trading analysis. Built with modern Python tools, it offers real-time option pricing, comprehensive Greek calculations, and professional-grade visualization.
- π° P&L-First Approach: Immediate profit/loss visualization with customizable entry prices
- π¨ Interactive Heatmaps: Cell-based 10Γ10 grids with clean value annotations
- π Side-by-Side Comparison: Compare Call and Put options simultaneously
- π Professional Visualizations: Publication-quality charts with color-coded insights
- πΎ Historical Tracking: SQLite database for calculation persistence and analysis
- Cell-based Display: Replaced continuous contour plots with discrete 10Γ10 cell grids
- Value Annotations: Each cell displays its numerical value for precise analysis
- Smart Color Coding:
- P&L: Green (profit) β Yellow (breakeven) β Red (loss)
- Prices: Green (high) β Yellow (mid) β Red (low)
- Enhanced Readability: Clean cell boundaries with optimized text contrast
- Entry Price Control: Dedicated input field for option purchase price
- Auto-Population: Automatically populated with calculated fair value
- Manual Override: Modify entry price for "what-if" scenario analysis
- Real-time P&L: Instant profit/loss calculation:
Current Value - Purchase Price
- Default P&L View: Opens directly to profit/loss analysis
- Dual Heatmap Comparison: Side-by-side Call and Put P&L scenarios
- Toggle Functionality: Switch between "P&L View" and "Price View" modes
- Comprehensive Metrics: Fair value, purchase price, P&L ($), and P&L (%) displayed prominently
- Diverging Colormap: RdYlGn palette centered at zero for P&L
- Visual Clarity: Profit zones (green) and loss zones (red) immediately identifiable
- Breakeven Zones: Yellow/white regions near Β±$0.50 for marginal scenarios
- β European call and put option valuation
- β Real-time fair value calculation
- β Put-call parity verification
- β Edge case handling (expiration, zero volatility)
- Delta (Ξ): Sensitivity to underlying price changes
- Gamma (Ξ): Rate of change of Delta
- Vega (Ξ½): Sensitivity to volatility changes
- Theta (Ξ): Time decay measurement
- Rho (Ο): Sensitivity to interest rate changes
-
P&L Analysis (Primary Tab)
- Side-by-side Call/Put P&L heatmaps
- Toggle between P&L and Price views
- Customizable spot and volatility ranges
-
Price Heatmaps
- Single option detailed analysis
- Spot price vs. volatility sensitivity
-
Greeks Heatmaps
- Visualize any Greek across parameter space
- Delta, Gamma, Vega, Theta, Rho support
-
Payoff Diagrams
- Classic profit/loss at expiration
- Breakeven point identification
- SQLite persistence layer
- Calculation history tracking
- Advanced filtering by option type
- CSV export functionality
- Statistical summaries
- Python: 3.9 or higher
- pip: Package manager (usually bundled with Python)
- Git: For cloning the repository
git clone https://github.com/yourusername/blackschole_option.git
cd blackschole_optionmacOS/Linux:
python3 -m venv venv
source venv/bin/activateWindows:
python -m venv venv
venv\Scripts\activatepip install -r requirements.txtRequired packages:
numpy>=1.24.0- Numerical computationsscipy>=1.10.0- Statistical functionspandas>=2.0.0- Data manipulationmatplotlib>=3.7.0- Plottingseaborn>=0.12.0- Statistical visualizationsstreamlit>=1.28.0- Web interfacepytest>=7.4.0- Testing framework
streamlit run app/streamlit_app.pyOR if you encounter path issues:
python3 -m streamlit run app/streamlit_app.pyThe application will automatically open in your default browser at:
- Local URL:
http://localhost:8501 - Network URL: Your local IP (displayed in terminal)
-
Sidebar Inputs:
- Select option type (Call/Put)
- Enter purchase/entry price (auto-populated with fair value)
- Set market parameters (S, K, T, Ο, r)
-
Main Dashboard:
- View fair value, purchase price, and P&L metrics
- See moneyness status (ITM/ATM/OTM)
- Check intrinsic and time value
-
Sensitivity Analysis:
- Navigate to "π° P&L Analysis" tab (default view)
- Compare Call vs Put scenarios side-by-side
- Toggle between P&L and Price views
- Explore Greeks and payoff diagrams
-
Database Operations:
- Save calculations for future reference
- View calculation history
- Export to CSV
The SQLite database is automatically created when you first run the application. No manual setup required!
Database Location: option_calculations.db (root directory)
If you need to manually initialize or reset the database:
# Using Python
python3 -c "from db.db_handler import get_handler; get_handler().initialize_db()"CREATE TABLE inputs (
calculation_id TEXT PRIMARY KEY,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
spot_price REAL NOT NULL,
strike_price REAL NOT NULL,
time_to_maturity REAL NOT NULL,
volatility REAL NOT NULL,
risk_free_rate REAL NOT NULL,
option_type TEXT NOT NULL CHECK(option_type IN ('call', 'put'))
);CREATE TABLE outputs (
calculation_id TEXT PRIMARY KEY,
option_price REAL NOT NULL,
delta REAL NOT NULL,
gamma REAL NOT NULL,
vega REAL NOT NULL,
theta REAL NOT NULL,
rho REAL NOT NULL,
FOREIGN KEY (calculation_id) REFERENCES inputs(calculation_id) ON DELETE CASCADE
);from db.db_handler import get_handler
handler = get_handler()
inputs = {
'spot_price': 100,
'strike_price': 100,
'time_to_maturity': 1.0,
'volatility': 0.2,
'risk_free_rate': 0.05,
'option_type': 'call'
}
outputs = {
'option_price': 10.45,
'delta': 0.637,
'gamma': 0.019,
'vega': 0.375,
'theta': -0.012,
'rho': 0.532
}
calc_id = handler.save_calculation(inputs, outputs)
print(f"Saved with ID: {calc_id}")# Get recent calculations
history = handler.get_calculation_history(limit=20)
# Filter by option type
call_history = handler.get_calculation_history(limit=50, option_type='call')
# Get as pandas DataFrame
df = handler.get_calculation_history_df(limit=100)stats = handler.get_statistics()
print(f"Total calculations: {stats['total_calculations']}")
print(f"Call options: {stats['call_count']}")
print(f"Put options: {stats['put_count']}")
print(f"Average price: ${stats['avg_option_price']:.2f}")View database contents (requires SQLite CLI):
sqlite3 option_calculations.db
.tables
SELECT * FROM inputs LIMIT 5;
.exitBackup database:
cp option_calculations.db option_calculations_backup_$(date +%Y%m%d).dbReset database (deletes all data):
rm option_calculations.db
# Database will be recreated on next app launch1. Open http://localhost:8501
2. Select "Call" option type
3. Enter parameters:
- Spot Price: $100
- Strike Price: $100
- Time to Maturity: 1.0 years
- Volatility: 20%
- Risk-Free Rate: 5%
4. Set purchase price: $10.45 (auto-filled)
5. View results:
- Fair Value: $10.45
- P&L: $0.00 (0%)
6. Adjust spot price to $105 β See updated P&L
7. Navigate to "P&L Analysis" tab
8. Compare Call vs Put scenarios
9. Save calculation to database
from core.black_scholes import BlackScholesModel
model = BlackScholesModel()
# Price a call option
call = model.call_price(S=100, K=100, T=1.0, sigma=0.2, r=0.05)
print(f"Call: ${call:.2f}") # Call: $10.45
# Price a put option
put = model.put_price(S=100, K=100, T=1.0, sigma=0.2, r=0.05)
print(f"Put: ${put:.2f}") # Put: $5.57greeks = model.greeks(S=100, K=100, T=1.0, sigma=0.2, r=0.05, option_type='call')
for name, value in greeks.items():
print(f"{name.capitalize()}: {value:.4f}")from visuals.heatmap import OptionVisualizer
viz = OptionVisualizer()
params = {
'spot_price': 100,
'strike_price': 100,
'time_to_maturity': 1.0,
'volatility': 0.2,
'risk_free_rate': 0.05,
'option_type': 'call'
}
# P&L heatmap
fig = viz.plot_pnl_heatmap(
entry_price=10.45,
base_params=params,
show_percentage=False
)
fig.savefig('pnl_analysis.png', dpi=300, bbox_inches='tight')blackschole_option/
βββ core/
β βββ __init__.py
β βββ black_scholes.py # Pricing engine & Greeks
βββ app/
β βββ __init__.py
β βββ streamlit_app.py # Web interface (Sigma Option UI)
βββ visuals/
β βββ __init__.py
β βββ heatmap.py # Heatmap visualizations (10Γ10 grids)
βββ db/
β βββ __init__.py
β βββ schema.sql # SQLite schema
β βββ db_handler.py # Database operations
βββ tests/
β βββ __init__.py
β βββ test_black_scholes.py # 41 unit tests
β βββ test_db_handler.py # 36 unit tests
βββ requirements.txt # Python dependencies
βββ milestones.md # Implementation roadmap
βββ README.md # This file
βββ option_calculations.db # SQLite database (auto-created)
Run the complete test suite:
# All tests
pytest
# With coverage report
pytest --cov=core --cov=db --cov=visuals tests/
# Verbose output
pytest -v
# Specific test file
pytest tests/test_black_scholes.pyTest Coverage Summary:
- Total Tests: 77 passing
- Black-Scholes Model: 41 tests (pricing, Greeks, edge cases, validation)
- Database Handler: 36 tests (CRUD, constraints, queries, statistics)
Call Option:
C = SβN(dβ) - Ke^(-rT)N(dβ)
Put Option:
P = Ke^(-rT)N(-dβ) - SβN(-dβ)
Where:
dβ = [ln(Sβ/K) + (r + ΟΒ²/2)T] / (ΟβT)
dβ = dβ - ΟβT
- Sβ: Current spot price
- K: Strike price
- T: Time to maturity (years)
- Ο: Volatility (annualized)
- r: Risk-free rate (annualized)
- N(x): Cumulative standard normal distribution
- European-style exercise only
- No dividends during option life
- Constant volatility and risk-free rate
- Log-normal distribution of stock prices
- Frictionless markets (no transaction costs/taxes)
- Continuous trading possible
- Unlimited borrowing/lending at risk-free rate
| Category | Technology |
|---|---|
| Core Language | Python 3.9+ |
| Scientific Computing | NumPy, SciPy |
| Data Analysis | Pandas |
| Visualization | Matplotlib, Seaborn |
| Web Framework | Streamlit |
| Database | SQLite3 |
| Testing | pytest, pytest-cov |
| Version Control | Git |
- Real-time market data integration (Yahoo Finance API)
- Implied volatility surface visualization
- Historical volatility calculation
- Multi-leg option strategies (spreads, straddles, strangles)
- Docker containerization
- REST API (FastAPI)
- Cloud deployment (AWS/Heroku/Railway)
- User authentication system
- WebSocket for real-time updates
- American option pricing (Binomial tree)
- Monte Carlo simulation engine
- Exotic options (Asian, Barrier, Lookback)
- Volatility smile/skew modeling
The application will be deployed to a public URL for easy access without local installation. Planned hosting options:
- Streamlit Cloud (Primary)
- Heroku (Alternative)
- Railway (Alternative)
Current Status: Local deployment only Expected Launch: [TBD]
Check back soon for the live demo link!
This project is licensed under the MIT License. See LICENSE file for details.
Duong Hong Duc Grinnell College
This project demonstrates:
- Quantitative finance modeling
- Full-stack development skills
- Data visualization expertise
- Software engineering best practices
- Database design and management
- Hull, J. C. (2017). Options, Futures, and Other Derivatives
- Black, F., & Scholes, M. (1973). The Pricing of Options and Corporate Liabilities
- Merton, R. C. (1973). Theory of Rational Option Pricing
- Black-Scholes Model - Wikipedia
- Option Greeks - Investopedia
- Put-Call Parity - CFI
- Streamlit Documentation
πΏ Sigma Option
Professional Black-Scholes option pricing with interactive P&L analysis
Built with β€οΈ for quantitative finance enthusiasts