This repository contains three advanced quantitative finance tasks implemented in Python, covering portfolio hedging, market making, and options pricing with local volatility models.
- Task 1: Portfolio Hedging with Risk Management
- Task 2: Automated Market Making Strategy
- Task 3: Options Pricing with Local Volatility Models
- Installation and Setup
Implements two approaches to hedge portfolio risk using historical stock returns data: Linear Programming optimization and LASSO regression with cross-validation.
hedge.py
- Linear programming approach using CVaR optimizationlasso_CV.py
- LASSO regression with cross-validation approach
Standard Input: <portfolio_id> <pnl_1> <pnl_2> ... <pnl_T>
Example:
PORTFOLIO_001 -2.5 1.8 -0.9 2.1 -1.2 0.8 ...
Required CSV Files:
stocks_returns.csv
- Historical stock returns (T×N matrix where T=time periods, N=stocks)stocks_metadata.csv
- Stock metadata with columns:Stock_Id
,Capital_Cost
<Stock_Id> <Quantity>
<Stock_Id> <Quantity>
...
- Objective: Minimize Conditional Value at Risk (CVaR) at 95% confidence level
- Constraints:
- Maximum position size per stock: 10,000 shares
- Position cost penalty to discourage unnecessary large positions
- Method: Uses scipy's linear programming solver with CVaR optimization
- Key Parameters:
VAR_CONF_LEVEL = 0.95
(VaR confidence level)LAMBDA_COST = 1e-5
(position cost penalty)MAX_QTY = 10000
(maximum shares per stock)
- Objective: Find sparse hedge portfolio using regularized regression
- Method: LASSO with 3-fold cross-validation to select optimal regularization
- Features:
- Automatic feature standardization
- Sparse solution (many zero positions)
- Cross-validation for hyperparameter tuning
# Linear Programming Approach
echo "PORTFOLIO_001 -2.5 1.8 -0.9 2.1" | python hedge.py
# LASSO Regression Approach
echo "PORTFOLIO_001 -2.5 1.8 -0.9 2.1" | python lasso_CV.py
Implements a sophisticated automated market making strategy that dynamically quotes bid/ask prices based on market conditions, inventory management, and risk factors.
amm_strategy.py
- Complete market making implementation with backtesting
orderbook_train.csv
- Market depth data with columns:timestamp
,bid_1_price
,bid_1_size
,ask_1_price
,ask_1_size
public_trades_train.csv
- Trade execution data with columns:timestamp
,price
,side
(buy/sell)
submission.csv
- Generated quotes with columns:timestamp
,bid_price
,ask_price
tick_size = 0.1
- Minimum price incrementlot_size = 2
- Base order sizemax_inventory = 20
- Maximum position limitwindow = 50
- Historical data window for calculations
-
Dynamic Spread Calculation
- Base spread: 2 ticks + volatility and imbalance adjustments
- Volatility factor: Adapts to recent price movements
- Liquidity factor: Adjusts based on order book depth
-
Inventory Management
- Inventory penalty: Skews quotes when position is large
- Position limits: Stops quoting when near maximum inventory
- Adaptive lot sizing: Reduces order size in volatile conditions
-
Market Microstructure Signals
- Order imbalance: Adjusts quotes based on bid/ask size ratio
- Momentum detection: Uses EMA trend analysis
- Micro-price calculation: Weighted average of bid/ask
-
Risk Controls
- Maximum inventory limits with gradual and hard stops
- Volatility-based spread widening
- Adaptive position sizing
python amm_strategy.py
The script will:
- Load orderbook and trade data
- Run the market making simulation for 3000 timestamps
- Generate quotes based on the strategy
- Save results to
submission.csv
The strategy tracks:
- Total P&L (realized + unrealized)
- Number of trades executed
- Quote refresh frequency
- Final inventory position
Implements advanced options pricing using both Black-Scholes with implied volatility surfaces and Dupire local volatility models for pricing exotic basket options with knock-out features.
black-scholes.py
- Black-Scholes implementation with implied volatility calibrationdupires.py
- Dupire local volatility model implementation
- Assets: DTC, DFC, DEC (3 correlated stocks)
- Initial Prices: All start at $100
- Risk-free Rate: 5% annual
- Correlation Matrix:
DTC DFC DEC 1.00 0.75 0.50 (DTC) 0.75 1.00 0.25 (DFC) 0.50 0.25 1.00 (DEC)
Market calibration data includes European call option prices for:
- Strikes: [50, 75, 100, 125, 150]
- Maturities: [1Y, 2Y, 5Y]
- All three underlying assets
Basket Options with Knock-out Features:
- Underlying: Equally-weighted basket of DTC, DFC, DEC
- Types: European Call and Put options
- Knock-out Barriers: 150, 175, 200
- Strikes: 50, 75, 100, 125
- Maturities: 2Y, 5Y
- Feature: Up-and-out barrier (option expires worthless if basket ever reaches barrier)
-
Implied Volatility Calibration:
- Extracts implied volatilities from market call prices
- Creates volatility surfaces using bivariate spline interpolation
- Uses constant volatility per asset for simulation
-
Monte Carlo Simulation:
- 200,000 paths with 252 steps per year
- Correlated Brownian motion using Cholesky decomposition
- Knock-out monitoring at each time step
-
Local Volatility Surface Construction:
- Computes partial derivatives of call prices (∂C/∂K, ∂²C/∂K², ∂C/∂T)
- Applies Dupire formula: σ²(K,T) = (∂C/∂T + rK∂C/∂K) / (½K²∂²C/∂K²)
- Creates local volatility surfaces for each asset
-
Enhanced Monte Carlo:
- Path-dependent volatility using local vol surfaces
- More accurate pricing for exotic options
- State-dependent volatility at each simulation step
σ²ₗᵥ(K,T) = (∂C/∂T + rK∂C/∂K) / (½K²∂²C/∂K²)
Call: max(Basket(T) - K, 0) × 𝟙{max(Basket(t)) < Barrier for all t ∈ [0,T]}
Put: max(K - Basket(T), 0) × 𝟙{max(Basket(t)) < Barrier for all t ∈ [0,T]}
Where Basket(t) = (S₁(t) + S₂(t) + S₃(t)) / 3
# Black-Scholes with Implied Volatility
python black-scholes.py
# Dupire Local Volatility Model
python dupires.py
Both scripts will:
- Calibrate volatility surfaces from market data
- Run Monte Carlo simulations for all 36 basket options
- Output prices in CSV format:
Id,Price
Id,Price
1,42.542045
2,51.175706
3,53.984200
...
36,13.051026
pip install numpy pandas scipy scikit-learn matplotlib
- Python 3.7+
- All code tested with standard scientific Python stack
project/
├── hedging_strategy/
│ ├── hedge.py
│ ├── lasso_CV.py
│ ├── stocks_returns.csv
│ └── stocks_metadata.csv
├── automated_market_making/
│ ├── amm_strategy.py
│ ├── orderbook_train.csv
│ ├── public_trades_train.csv
│ └── submission.csv (generated)
├── monte_carlo_pricing/
│ ├── black-scholes.py
│ └── dupires.py
└── README.md
- Task 1: Runs in seconds for typical portfolio sizes
- Task 2: Processes 3000 market timestamps efficiently
- Task 3: Monte Carlo with 200K paths takes several minutes
- Risk Management: All implementations include sophisticated risk controls
- Market Realism: Models incorporate real market microstructure effects
- Numerical Stability: Robust handling of edge cases and numerical precision
- Scalability: Efficient implementations suitable for production use
-
Clone and setup:
git clone https://github.com/who-else-but-arjun/Quant_25.git cd Quant_25 pip install -r requirements.txt
-
Run individual tasks:
# Portfolio Hedging echo "PORTFOLIO_001 -2.5 1.8 -0.9" | python hedge.py # Market Making python amm_strategy.py # Options Pricing python black-scholes.py
-
Check outputs in respective directories
Each task is self-contained and can be run independently with the provided sample data or your own datasets following the specified input formats.