[FICC] Valuation 처돌이의 Quantlib 스터디 (feat. Chat GPT)

허상범·2023년 9월 17일
0

Finance

목록 보기
9/9

주식을 넘어, 이제는 FICC까지 Valuation하는 것에 관심이 많아졌다.

Quantlib은 FICC에 대한 Sell-side Pricing 측면에서 가장 강력한 툴로 자리잡고 있기 때문에 Python OOP에 좀만 더 익숙해지고 나면 Quantlib을 열심히 써볼 생각이다.

아래는 Quantlib에 대한 brief walkthrough를 Chat GPT에게 요청한 내용과 상품군 별로 샘플 코드를 작성해달라는 요청에 대한 응답 결과이다.

Please walk me through Quantlib.

QuantLib is a powerful open-source library for quantitative finance and financial instrument pricing and analysis. It is written in C++, but it also provides Python bindings, making it accessible to Python developers. QuantLib is widely used in the finance industry for tasks such as pricing derivatives, risk management, and financial instrument modeling. Let's break down the structure of the QuantLib library in Python.

  1. Installation:
    You can install the QuantLib-Python package using pip:

    pip install QuantLib-Python
  2. Modules:
    QuantLib is organized into various modules, each of which focuses on a specific aspect of quantitative finance. Some of the core modules include:

    • QuantLib:

      • This is the main module that provides the core functionality of the QuantLib library. It contains classes and functions for modeling financial instruments, term structures, and various financial calculations.
    • QuantLib.PricingEngines:

      • This module contains pricing engines for different types of financial instruments such as options, bonds, and swaps. These engines are used to calculate the fair value of these instruments.
    • QuantLib.Instruments:

      • Here, you'll find classes that represent various financial instruments, including options (e.g., EuropeanOption), bonds (e.g., FixedRateBond), and swaps (e.g., InterestRateSwap).
    • QuantLib.Calendars:

      • This module deals with financial calendars, which are essential for calculating dates related to financial instruments. It includes classes for different financial calendars, holidays, and business day conventions.
    • QuantLib.Currencies:

      • This module provides classes to work with different currencies, including currency codes, exchange rates, and conversion functions.
    • QuantLib.MarketData:

      • This module deals with market data such as interest rates, yield curves, and volatility surfaces. It provides tools to manage and interpolate market data.
    • QuantLib.Time:

      • Time-related calculations are crucial in finance. This module contains classes and functions for managing dates, time periods, and day counting conventions.
    • QuantLib.Solvers:

      • Solvers are used to find solutions to various mathematical problems, such as root finding and optimization. This module provides tools for solving financial equations.
  3. Usage:
    To use QuantLib in Python, you typically start by importing the necessary modules and classes. You can create financial instruments, set up pricing engines, and perform calculations based on your specific needs.

    Here's a simple example of how to use QuantLib in Python to calculate the price of a European call option:

    from QuantLib import *
    
    # Define option parameters
    option_type = Option.Call
    underlying_price = 100
    strike_price = 105
    maturity_date = Date(15, 9, 2024)
    volatility = 0.2
    risk_free_rate = 0.05
    
    # Create QuantLib objects
    option = EuropeanOption(PlainVanillaPayoff(option_type, strike_price), EuropeanExercise(maturity_date))
    spot_handle = QuoteHandle(SimpleQuote(underlying_price))
    flat_ts = YieldTermStructureHandle(FlatForward(maturity_date, QuoteHandle(SimpleQuote(risk_free_rate)), Actual360()))
    flat_vol_ts = BlackVolTermStructureHandle(BlackConstantVol(maturity_date, NullCalendar(), QuoteHandle(SimpleQuote(volatility)), Actual360()))
    
    # Create the Black-Scholes process
    bs_process = BlackScholesProcess(spot_handle, flat_ts, flat_vol_ts)
    
    # Create a pricing engine
    engine = AnalyticEuropeanEngine(bs_process)
    
    # Set the pricing engine for the option
    option.setPricingEngine(engine)
    
    # Calculate the option price
    option_price = option.NPV()
    
    print("Option Price:", option_price)

please write me sample codes of pricing financial products including Fixed Income, Interest Rate, Currency, and Commodities

Certainly! Below are sample code snippets for pricing various financial products, including Fixed Income instruments, Interest Rate derivatives, Currency derivatives, and Commodities using QuantLib in Python. Please note that these are simplified examples for demonstration purposes, and real-world pricing would involve more complex inputs and market data.

1. Pricing a Fixed Income Bond:

from QuantLib import *

# Define bond parameters
face_value = 1000
issue_date = Date(15, 9, 2021)
maturity_date = Date(15, 9, 2031)
coupon_rate = 0.05
settlement_date = Date(15, 9, 2023)

# Create QuantLib objects
fixed_rate_bond = FixedRateBond(0, NullCalendar(), [face_value], [coupon_rate], Actual360())
bond_schedule = Schedule(issue_date, maturity_date, Period(Annual), NullCalendar(), Following, Following, DateGeneration.Backward, False)
fixed_rate_bond.setPricingEngine(DiscountingBondEngine(YieldTermStructureHandle(FlatForward(settlement_date, QuoteHandle(SimpleQuote(0.05)), Actual360()))))

# Calculate bond price
bond_price = fixed_rate_bond.cleanPrice()
print("Fixed Income Bond Price:", bond_price)

2. Pricing an Interest Rate Swap:

from QuantLib import *

# Define swap parameters
notional = 1000000
start_date = Date(15, 9, 2023)
maturity_date = Date(15, 9, 2033)
fixed_rate = 0.04
floating_rate = 6-months LIBOR
spread = 0.01

# Create QuantLib objects
fixed_leg = FixedRateLeg(Schedule(start_date, maturity_date, Period(Semiannual), NullCalendar(), ModifiedFollowing, ModifiedFollowing, DateGeneration.Forward, False), Actual360(), [fixed_rate])
floating_leg = IborLeg(Schedule(start_date, maturity_date, Period(Semiannual), NullCalendar(), ModifiedFollowing, ModifiedFollowing, DateGeneration.Forward, False), floating_rate, Actual360())

swap = Swap(fixed_leg, floating_leg)

# Set up the pricing engine
discount_curve = YieldTermStructureHandle(FlatForward(start_date, QuoteHandle(SimpleQuote(0.035)), Actual360()))
swap.setPricingEngine(DiscountingSwapEngine(discount_curve))

# Calculate the swap's NPV
swap_npv = swap.NPV()
print("Interest Rate Swap NPV:", swap_npv)

3. Pricing a Currency Option:

from QuantLib import *

# Define option parameters
option_type = Option.Put
strike_price = 1.25
expiry_date = Date(15, 9, 2024)
spot_price = 1.20
volatility = 0.15
interest_rate = 0.03

# Create QuantLib objects
payoff = PlainVanillaPayoff(option_type, strike_price)
exercise = EuropeanExercise(expiry_date)
european_option = EuropeanOption(payoff, exercise)

spot_handle = QuoteHandle(SimpleQuote(spot_price))
rate_handle = YieldTermStructureHandle(FlatForward(expiry_date, QuoteHandle(SimpleQuote(interest_rate)), Actual360()))
vol_handle = BlackVolTermStructureHandle(BlackConstantVol(expiry_date, NullCalendar(), QuoteHandle(SimpleQuote(volatility)), Actual360()))
process = BlackScholesProcess(spot_handle, rate_handle, vol_handle)

# Set up the pricing engine
engine = AnalyticEuropeanEngine(process)
european_option.setPricingEngine(engine)

# Calculate the option price
option_price = european_option.NPV()
print("Currency Option Price:", option_price)

4. Pricing a Commodity Forward:

from QuantLib import *

# Define forward contract parameters
commodity_price = 50.0
delivery_date = Date(15, 9, 2024)
forward_price = 55.0
risk_free_rate = 0.02

# Create QuantLib objects
spot_handle = QuoteHandle(SimpleQuote(commodity_price))
forward_curve = YieldTermStructureHandle(FlatForward(delivery_date, QuoteHandle(SimpleQuote(forward_price)), Actual360()))

commodity_forward = Forward(spot_handle, forward_curve, delivery_date)

# Calculate the forward price
forward_price = commodity_forward.NPV()
print("Commodity Forward Price:", forward_price)

These are simplified examples to demonstrate how to price different types of financial products using QuantLib in Python. In practice, you would need to provide more accurate market data and handle various instrument-specific details for precise pricing.

profile
Engineering & Science, Since 2021 | Finance, Backend, Data

0개의 댓글