Python Advanced - Quantitative Finance with PyQuantLib
Implementing quantitative finance models and algorithms with PyQuantLib
PyQuantLib is a Python library that provides a comprehensive framework for quantitative finance. It is a wrapper for QuantLib, a popular open-source library for modeling, trading, and risk management in real-life. This tutorial explores how to use PyQuantLib for implementing quantitative finance models and algorithms in Python.
Key Points:
- PyQuantLib is a Python wrapper for the QuantLib library.
- QuantLib is widely used for modeling, trading, and risk management in finance.
- Using PyQuantLib allows you to implement advanced quantitative finance models and algorithms in Python.
Installing PyQuantLib
To use PyQuantLib, you need to install it using pip:
pip install QuantLib-Python
Basic Usage of PyQuantLib
Here is an example of using PyQuantLib to create a simple bond pricing model:
import QuantLib as ql
# Set the evaluation date
today = ql.Date(1, 1, 2024)
ql.Settings.instance().evaluationDate = today
# Define the bond characteristics
issue_date = ql.Date(1, 1, 2020)
maturity_date = ql.Date(1, 1, 2030)
tenor = ql.Period(ql.Annual)
calendar = ql.UnitedStates()
bussiness_convention = ql.Unadjusted
date_generation = ql.DateGeneration.Backward
month_end = False
schedule = ql.Schedule(issue_date, maturity_date, tenor, calendar, bussiness_convention,
bussiness_convention, date_generation, month_end)
# Define the fixed rate bond
coupon_rate = 0.05
coupons = [coupon_rate]
settlement_days = 3
face_value = 100
fixed_rate_bond = ql.FixedRateBond(settlement_days, face_value, schedule, coupons, ql.ActualActual())
# Define the yield term structure
spot_dates = [ql.Date(1, 1, 2024), ql.Date(1, 1, 2025), ql.Date(1, 1, 2026), ql.Date(1, 1, 2027)]
spot_rates = [0.02, 0.025, 0.03, 0.035]
day_count = ql.ActualActual()
calendar = ql.UnitedStates()
interpolation = ql.Linear()
compounding = ql.Compounded
compounding_frequency = ql.Annual
spot_curve = ql.ZeroCurve(spot_dates, spot_rates, day_count, calendar, interpolation, compounding, compounding_frequency)
spot_curve_handle = ql.YieldTermStructureHandle(spot_curve)
# Pricing the bond
bond_engine = ql.DiscountingBondEngine(spot_curve_handle)
fixed_rate_bond.setPricingEngine(bond_engine)
# Output the bond's Net Present Value (NPV)
print(f"Net Present Value: {fixed_rate_bond.NPV():.2f}")
Black-Scholes Option Pricing
Here is an example of using PyQuantLib to price a European call option using the Black-Scholes model:
# Define the option characteristics
maturity_date = ql.Date(1, 1, 2025)
spot_price = 100
strike_price = 105
volatility = 0.2 # the historical vols for a year
dividend_rate = 0.02
option_type = ql.Option.Call
risk_free_rate = 0.01
# Create the option
payoff = ql.PlainVanillaPayoff(option_type, strike_price)
exercise = ql.EuropeanExercise(maturity_date)
european_option = ql.VanillaOption(payoff, exercise)
# Define the market data
calendar = ql.UnitedStates()
day_count = ql.Actual365Fixed()
spot_handle = ql.QuoteHandle(ql.SimpleQuote(spot_price))
flat_ts = ql.YieldTermStructureHandle(ql.FlatForward(today, risk_free_rate, day_count))
dividend_yield = ql.YieldTermStructureHandle(ql.FlatForward(today, dividend_rate, day_count))
flat_vol_ts = ql.BlackVolTermStructureHandle(ql.BlackConstantVol(today, calendar, volatility, day_count))
# Create the Black-Scholes process
bsm_process = ql.BlackScholesMertonProcess(spot_handle, dividend_yield, flat_ts, flat_vol_ts)
# Set the pricing engine
european_option.setPricingEngine(ql.AnalyticEuropeanEngine(bsm_process))
# Output the option's Net Present Value (NPV)
print(f"Option NPV: {european_option.NPV():.2f}")
Interest Rate Models
Here is an example of using the Hull-White model to simulate interest rates:
# Define the Hull-White model
mean_reversion = 0.1
volatility = 0.01
hw_model = ql.HullWhite(spot_curve_handle, mean_reversion, volatility)
# Simulate the interest rates
dates = [ql.Date(1, 1, 2025), ql.Date(1, 1, 2026), ql.Date(1, 1, 2027), ql.Date(1, 1, 2028)]
simulated_rates = [hw_model.forwardRate(d, d, day_count, ql.Simple).rate() for d in dates]
# Output the simulated rates
print("Simulated interest rates:")
for date, rate in zip(dates, simulated_rates):
print(f"{date}: {rate:.4f}")
Calculating Greeks
Here is an example of calculating the Greeks for a European call option:
# Calculate Delta
delta = european_option.delta()
print(f"Delta: {delta:.4f}")
# Calculate Gamma
gamma = european_option.gamma()
print(f"Gamma: {gamma:.4f}")
# Calculate Vega
vega = european_option.vega()
print(f"Vega: {vega:.4f}")
# Calculate Theta
theta = european_option.theta()
print(f"Theta: {theta:.4f}")
# Calculate Rho
rho = european_option.rho()
print(f"Rho: {rho:.4f}")
Summary
In this tutorial, you learned about implementing quantitative finance models and algorithms using PyQuantLib in Python. PyQuantLib is a powerful library that wraps the QuantLib library, providing a comprehensive framework for quantitative finance. Understanding how to use PyQuantLib for bond pricing, option pricing, interest rate modeling, and calculating Greeks can help you implement advanced financial models and algorithms in your Python applications.