Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
""" Simple example pricing a European option
using a Black&Scholes Merton process."""
from quantlib.instruments.api import (EuropeanExercise, PlainVanillaPayoff, Put,
VanillaOption)
from quantlib.pricingengines.api import AnalyticEuropeanEngine
from quantlib.processes.black_scholes_process import BlackScholesMertonProcess
from quantlib.quotes import SimpleQuote
from quantlib.settings import Settings
from quantlib.time.api import TARGET, Actual365Fixed, today
from quantlib.termstructures.yields.api import FlatForward
from quantlib.termstructures.volatility.api import BlackConstantVol
settings = Settings.instance()
calendar = TARGET()
offset = 366
todays_date = today() - offset
settlement_date = todays_date + 2
settings.evaluation_date = todays_date
# options parameters
option_type = Put
underlying = 36
strike = 40
dividend_yield = 0.00
risk_free_rate = 0.06
volatility = 0.20
maturity = settlement_date + 363
risk_free_rate = FlatForward(
reference_date=settlement_date,
forward=0.06,
daycounter=Actual365Fixed()
)
# option parameters
exercise = AmericanExercise(
earliest_exercise_date=settlement_date,
latest_exercise_date=Date(17, May, 1999)
)
payoff = PlainVanillaPayoff(Put, 40.0)
# market data
underlying = SimpleQuote(36.0)
volatility = BlackConstantVol(todays_date, TARGET(), 0.20,
Actual365Fixed())
dividend_yield = FlatForward(
reference_date=settlement_date,
forward=0.00,
daycounter=Actual365Fixed()
)
# report
header = '%19s' % 'method' + ' |' + \
' |'.join(['%17s' % tag for tag in ['value',
'estimated error',
'actual error']])
print()
print(header)
print('-' * len(header))
def get_term_structure(df_libor, dtObs):
settings = Settings()
# Market information
calendar = TARGET()
# must be a business day
eval_date = calendar.adjust(Date.from_datetime(dtObs))
settings.evaluation_date = eval_date
settlement_days = 2
settlement_date = calendar.advance(eval_date, settlement_days, Days)
# must be a business day
settlement_date = calendar.adjust(settlement_date)
depositData = [[1, Months, 'Libor1M'],
[3, Months, 'Libor3M'],
[6, Months, 'Libor6M']]
swapData = [[1, Years, 'Swap1Y'],
[2, Years, 'Swap2Y'],
# This code throws a QuantLib::Error that terminates python
# Settings is set by default to today's date.
# If dt_payment is in the past, a QuantLib::Error is thrown from c++
import logging
from quantlib.quotes import SimpleQuote
from quantlib.termstructures.yields.api import FlatForward
from quantlib.time.api import Actual360, Date, NullCalendar, TARGET
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
calendar = TARGET()
date_today = Date(6,9,2011)
date_payment = Date(6,12,2000)
settlement_days = 2
quote = SimpleQuote(value=0.03)
term_structure = FlatForward(
settlement_days = settlement_days,
quote = quote,
calendar = NullCalendar(),
daycounter = Actual360()
)
try:
df_1 = term_structure.discount(date_payment)
def zero_rate(term_structure, days, dt_settlement, calendar=TARGET()):
"""
Compute zero-coupon rate, continuous ACT/365 from settlement date to given
maturity expressed in calendar days
Return
- array of maturity dates
- array of zero-coupon rates
"""
dtMat = [calendar.advance(pydate_to_qldate(dt_settlement), d, Days)
for d in days]
df = np.array([term_structure.discount(dt) for dt in dtMat])
dtMat = [qldate_to_pydate(dt) for dt in dtMat]
dtToday = qldate_to_pydate(dt_settlement)
dt = np.array([(d - dtToday).days / 365.0 for d in dtMat])
zc = -np.log(df) / dt
def heston_helpers(df_option, dtTrade=None, df_rates=None, ival=None):
"""
Create array of heston options helpers
"""
if dtTrade is None:
dtTrade = df_option['dtTrade'][0]
DtSettlement = pydate_to_qldate(dtTrade)
settings = Settings()
settings.evaluation_date = DtSettlement
calendar = TARGET()
if df_rates is None:
df_tmp = DataFrame.filter(df_option, items=['dtExpiry', 'IR', 'IDIV'])
grouped = df_tmp.groupby('dtExpiry')
df_rates = grouped.agg(lambda x: x[0])
# convert data frame (date/value) into zero curve
# expect the index to be a date, and 1 column of values
risk_free_ts = df_to_zero_curve(df_rates['R'], dtTrade)
dividend_ts = df_to_zero_curve(df_rates['D'], dtTrade)
# back out the spot from any forward
iRate = df_option['R'][0]
iDiv = df_option['D'][0]
TTM = df_option['T'][0]
def zero_curve(ts, dtObs):
dtMax = ts.max_date
calendar = TARGET()
days = range(10, 365 * 20, 30)
dtMat = [min(dtMax, calendar.advance(Date.from_datetime(dtObs), d, Days))
for d in days]
# largest dtMat < dtMax, yet QL run time error
df = np.array([ts.discount(dt) for dt in dtMat])
dtMat = [pydate_from_qldate(dt) for dt in dtMat]
dtToday = dtObs.date()
dt = np.array([(d - dtToday).days / 365.0 for d in dtMat])
zc = -np.log(df) / dt
return (dtMat, zc)