Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions examples/american_option.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@
FOR A PARTICULAR PURPOSE. See the license for more details.
"""
from quantlib.instruments.api import AmericanExercise, VanillaOption, OptionType
from quantlib.instruments.payoffs import PlainVanillaPayoff
from quantlib.payoffs import PlainVanillaPayoff
from quantlib.pricingengines.api import BaroneAdesiWhaleyApproximationEngine
from quantlib.pricingengines.api import FdBlackScholesVanillaEngine
from quantlib.processes.black_scholes_process import BlackScholesMertonProcess
from quantlib.quotes import SimpleQuote
from quantlib.settings import Settings
from quantlib.time.api import Actual365Fixed, Date, May, TARGET
from quantlib.termstructures.volatility.api import BlackConstantVol
from quantlib.termstructures.yields.api import HandleYieldTermStructure, FlatForward
from quantlib.termstructures.volatility.api import BlackConstantVol, HandleBlackVolTermStructure
from quantlib.termstructures.yields.api import RelinkableHandleYieldTermStructure, FlatForward
from quantlib.methods.finitedifferences.solvers.fdmbackwardsolver \
import FdmSchemeDesc

Expand All @@ -25,7 +25,7 @@ def main():
Settings.instance().evaluation_date = todays_date
settlement_date = Date(17, May, 1998)

risk_free_rate = HandleYieldTermStructure()
risk_free_rate = RelinkableHandleYieldTermStructure()
risk_free_rate.link_to(
FlatForward(
reference_date=settlement_date,
Expand All @@ -43,9 +43,11 @@ def main():

# market data
underlying = SimpleQuote(36.0)
volatility = BlackConstantVol(todays_date, TARGET(), 0.20,
volatility = HandleBlackVolTermStructure(
BlackConstantVol(todays_date, TARGET(), 0.20,
Actual365Fixed())
dividend_yield = HandleYieldTermStructure()
)
dividend_yield = RelinkableHandleYieldTermStructure()
dividend_yield.link_to(
FlatForward(
reference_date=settlement_date,
Expand Down
6 changes: 3 additions & 3 deletions examples/basic_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
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, HandleYieldTermStructure
from quantlib.termstructures.yields.api import FlatForward, RelinkableHandleYieldTermStructure
from quantlib.termstructures.volatility.api import BlackConstantVol


Expand All @@ -36,8 +36,8 @@
underlyingH = SimpleQuote(underlying)

# bootstrap the yield/dividend/vol curves
flat_term_structure = HandleYieldTermStructure()
flat_dividend_ts = HandleYieldTermStructure()
flat_term_structure = RelinkableHandleYieldTermStructure()
flat_dividend_ts = RelinkableHandleYieldTermStructure()

flat_term_structure.link_to(
FlatForward(
Expand Down
Binary file modified examples/data/df_SPX_24jan2011.pkl
Binary file not shown.
4 changes: 2 additions & 2 deletions examples/option_valuation.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
from quantlib.termstructures.yields.api import (
PiecewiseYieldCurve, DepositRateHelper, BootstrapTrait, HandleYieldTermStructure
)
from quantlib.termstructures.volatility.api import BlackConstantVol
from quantlib.termstructures.volatility.api import BlackConstantVol, HandleBlackVolTermStructure
from quantlib.termstructures.yields.api import SwapRateHelper

def dividendOption():
Expand Down Expand Up @@ -169,7 +169,7 @@ def dividendOption():

print('Creating process')

bsProcess = BlackScholesProcess(underlying_priceH, HandleYieldTermStructure(riskFreeTS), flatVolTS)
bsProcess = BlackScholesProcess(underlying_priceH, HandleYieldTermStructure(riskFreeTS), HandleBlackVolTermStructure(flatVolTS))


# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Expand Down
56 changes: 24 additions & 32 deletions examples/scripts/SPX_Options.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
from __future__ import print_function
# -*- coding: utf-8 -*-
# <nbformat>3</nbformat>

# <markdowncell>

# Standardized Option Quotes Data Format
# ======================================
#
#
# To facilitate model calibration, a standard input format has been defined, which contains all the
# necessary data. The data is held in a [Panda](http://pandas.pydata.org) table, with one row per quote and
# 8 columns, as follows:
#
#
# * dtTrade: Quote date, or time stamp
# * Strike: Ditto
# * dtExpiry: Option expiry date
Expand All @@ -19,23 +18,23 @@
# * Type: European/American
# * PBid: Bid price
# * PAsk: Ask price
#
# Note that we do not include the dividend yield nor the risk-free rate in the data set: The
#
# Note that we do not include the dividend yield nor the risk-free rate in the data set: The
# implied forward price and risk-free rate are estimated from the call/put parity.
#
#
# SPX Option Data Processing
# --------------------------
#
#
# As an illustration, we provide below the procedure for converting raw SPX option data, as published by the [CBOE](http://www.cboe.com/DelayedQuote/QuoteTableDownload.aspx), into the standard input format.
#
#
# ### SPX Utility functions
#
#
# These functions parse the SPX option names, and extract expiry date and strike.

# <codecell>

import pandas
import dateutil, datetime
import pandas as pd
import dateutil
import re

def ExpiryMonth(s):
Expand All @@ -58,26 +57,26 @@ def parseSPX(s):
"""
Parse an SPX quote string, return expiry date and strike
"""
tokens = spx_symbol.split(s)
tokens = spx_symbol.split(s.iloc[0])

if len(tokens) == 1:
return {'dtExpiry': None, 'strike': -1}
return {'Strike': -1, 'dtExpiry': None}

year = 2000 + int(tokens[1])
day = int(tokens[2])
month = ExpiryMonth(tokens[3])
strike = float(tokens[4])

dtExpiry = datetime.date(year, month, day)
dtExpiry = pd.Timestamp(year=year, month=month, day=day)

return ({'dtExpiry': dtExpiry, 'strike': strike})
return {'Strike': strike, 'dtExpiry': dtExpiry}


# <markdowncell>

# ### Reading the SPX raw data file
#
# The csv file downloaded from the CBOE site can be converted into a standard panda table by the following function.
#
# The csv file downloaded from the CBOE site can be converted into a standard panda table by the following function.

# <codecell>

Expand All @@ -93,12 +92,12 @@ def read_SPX_file(option_data_file):

lineTwo = fid.readline()
dt = lineTwo.split('@')[0]
dtTrade = dateutil.parser.parse(dt).date()
dtTrade = pd.to_datetime(dt)

print('Dt Calc: %s Spot: %f' % (dtTrade, spot))

# read all option price records as a data frame
df = pandas.io.parsers.read_csv(option_data_file, header=0, sep=',', skiprows=[0,1])
df = pd.read_csv(option_data_file, header=0, sep=',', skiprows=[0,1])

# split and stack calls and puts
call_df = df[['Calls', 'Bid', 'Ask']]
Expand All @@ -109,35 +108,28 @@ def read_SPX_file(option_data_file):
put_df = put_df.rename(columns = {'Puts':'Spec', 'Bid.1':'PBid',
'Ask.1':'PAsk'})
put_df['Type'] = 'P'

df_all = call_df.append(put_df, ignore_index=True)
df_all = pd.concat([call_df, put_df], ignore_index=True)

# parse Calls and Puts columns for strike and contract month
# insert into data frame

cp = [parseSPX(s) for s in df_all['Spec']]
df_all['Strike'] = [x['strike'] for x in cp]
df_all['dtExpiry'] = [x['dtExpiry'] for x in cp]

df_all = pd.concat([df_all,
df_all[["Spec"]].apply(parseSPX, axis="columns", result_type="expand")],
axis=1)
del df_all['Spec']

df_all = df_all[(df_all['Strike'] > 0) & (df_all['PBid']>0) \
& (df_all['PAsk']>0)]

df_all['dtTrade'] = dtTrade
df_all['Spot'] = spot

return df_all

option_data_file = \
'../data/SPX-Options-24jan2011.csv'

if __name__ == '__main__':
option_data_file = '../data/SPX-Options-24jan2011.csv'
df_SPX = read_SPX_file(option_data_file)
print('%d records processed' % len(df_SPX))

# save a csv file and pickled data frame
df_SPX.to_csv('../data/df_SPX_24jan2011.csv', index=False)
df_SPX.to_pickle('../data/df_SPX_24jan2011.pkl', protocol=4)
df_SPX.to_pickle('../data/df_SPX_24jan2011.pkl')
print('File saved')

42 changes: 23 additions & 19 deletions examples/traits_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
from quantlib.quotes import SimpleQuote
from quantlib.settings import Settings
from quantlib.time.api import TARGET, Actual365Fixed, today, Date as QlDate
from quantlib.termstructures.yields.api import FlatForward
from quantlib.termstructures.volatility.equityfx.black_vol_term_structure \
import BlackConstantVol
from quantlib.termstructures.yields.api import FlatForward, HandleYieldTermStructure
from quantlib.termstructures.volatility.api import BlackConstantVol


settings = Settings.instance()
Expand All @@ -32,7 +31,7 @@
class OptionValuation(HasTraits):

# options parameters
option_type = Enum(Put, Call)
option_type = Enum(OptionType.Put, OptionType.Call)
underlying = Float(36)
strike = Float(40)
dividend_yield = Range(0.0, 0.5)
Expand All @@ -50,12 +49,6 @@ class OptionValuation(HasTraits):

### Traits view ##########################################################

traits_view = View(
Item('option_type', editor=EnumEditor(values={Put:'Put', Call:'Call'})),
'underlying', 'strike', 'dividend_yield', 'risk_free_rate',
'volatility', 'maturity',
HGroup( Item('option_npv', label='Option value'))
)

### Private protocol #####################################################

Expand All @@ -73,16 +66,20 @@ def _get_option_npv(self):
underlyingH = SimpleQuote(self.underlying)

# bootstrap the yield/dividend/vol curves
flat_term_structure = FlatForward(
reference_date = settlement_date,
forward = self.risk_free_rate,
daycounter = self.daycounter
flat_term_structure = HandleYieldTermStructure(
FlatForward(
reference_date = settlement_date,
forward = self.risk_free_rate,
daycounter = self.daycounter
)
)

flat_dividend_ts = FlatForward(
reference_date = settlement_date,
forward = self.dividend_yield,
daycounter = self.daycounter
flat_dividend_ts = HandleYieldTermStructure(
FlatForward(
reference_date = settlement_date,
forward = self.dividend_yield,
daycounter = self.daycounter
)
)

flat_vol_ts = BlackConstantVol(
Expand All @@ -105,10 +102,17 @@ def _get_option_npv(self):

return european_option.net_present_value

traits_view = View(
Item('option_type', editor=EnumEditor(values={OptionType.Put:'Put', OptionType.Call:'Call'})),
'underlying', 'strike', 'dividend_yield', 'risk_free_rate',
'volatility', 'maturity',
HGroup( Item('option_npv', label='Option value'))
)

if __name__ == '__main__':

model = OptionValuation()
model.configure_traits()
model.configure_traits(view=traits_view)


### EOF #######################################################################
55 changes: 53 additions & 2 deletions quantlib/indexes/ibor_index.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,29 @@ from quantlib.market.conventions.swap import params as swap_params
from quantlib.indexes.interest_rate_index cimport InterestRateIndex

cdef class IborIndex(InterestRateIndex):
"""Base class for Inter-Bank-Offered-Rate indexes (e.g. Libor, etc.).

Parameters
----------
family_name : str
The family name of the index.
tenor : :class:`~quantlib.time.date.Period`
The tenor of the index.
settlement_days : int
The number of settlement days.
currency : :class:`~quantlib.currency.currency.Currency`
The currency of the index.
fixing_calendar : :class:`~quantlib.time.calendar.Calendar`
The calendar used for fixing dates.
convention : int
The business day convention.
end_of_month : bool
Whether the end-of-month rule applies.
day_counter : :class:`~quantlib.time.daycounter.DayCounter`
The day counter for the index.
yts : :class:`~quantlib.termstructures.yield_term_structure.HandleYieldTermStructure`, optional
The yield term structure handle.
"""

def __init__(self, str family_name, Period tenor not None, Natural settlement_days,
Currency currency, Calendar fixing_calendar, int convention,
Expand All @@ -40,17 +63,20 @@ cdef class IborIndex(InterestRateIndex):
)

property business_day_convention:
"""The business day convention."""
def __get__(self):
cdef _ib.IborIndex* ref = <_ib.IborIndex*>self._thisptr.get()
return ref.businessDayConvention()

property end_of_month:
"""Whether the end-of-month rule applies."""
def __get__(self):
cdef _ib.IborIndex* ref = <_ib.IborIndex*>self._thisptr.get()
return ref.endOfMonth()

@property
def forwarding_term_structure(self):
"""The curve used to forecast fixings."""
cdef:
_ib.IborIndex* ref = <_ib.IborIndex*>self._thisptr.get()
HandleYieldTermStructure yts = HandleYieldTermStructure.__new__(HandleYieldTermStructure)
Expand All @@ -59,8 +85,16 @@ cdef class IborIndex(InterestRateIndex):

@staticmethod
def from_name(market, term_structure=HandleYieldTermStructure(), **kwargs):
"""
Create default IBOR for the market, modify attributes if provided
"""Create a default IBOR index for the given market.

Parameters
----------
market : str
The market name (e.g., 'USDLibor', 'Euribor').
term_structure : :class:`~quantlib.termstructures.yield_term_structure.HandleYieldTermStructure`, optional
The yield term structure handle.
**kwargs :
Additional keyword arguments to override default parameters.
"""

row = swap_params(market)
Expand All @@ -84,6 +118,23 @@ cdef class IborIndex(InterestRateIndex):


cdef class OvernightIndex(IborIndex):
"""Base class for overnight indexes.

Parameters
----------
family_name : str
The family name of the index.
settlement_days : int
The number of settlement days.
currency : :class:`~quantlib.currency.currency.Currency`
The currency of the index.
fixing_calendar : :class:`~quantlib.time.calendar.Calendar`
The calendar used for fixing dates.
day_counter : :class:`~quantlib.time.daycounter.DayCounter`
The day counter for the index.
yts : :class:`~quantlib.termstructures.yield_term_structure.HandleYieldTermStructure`, optional
The yield term structure handle.
"""
def __init__(self, str family_name, Natural settlement_days,
Currency currency, Calendar fixing_calendar,
DayCounter day_counter not None,
Expand Down
Loading
Loading